<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
package com.kaishengit.httclient;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by wanggs on 2017/7/27.
*/
public class Httpclient {
public static void main(String[] args) throws IOException {
// 创建了一个可以发出请求的客户端
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建一个Get请求
HttpGet httpGet = new HttpGet("http://www.pingwest.com/feed/");
// HttpPost httpPost = new HttpPost("http://www.pingwest.com/feed/"); POST请求
// 发出请求,并接受服务端相应
HttpResponse response = httpClient.execute(httpGet);
// 获取Http状态码
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// html 也就是获取相应输入流
InputStream inputStream = response.getEntity().getContent();
String result = IOUtils.toString(inputStream, "UTF-8");
inputStream.close();
System.out.println(result);
} else {
System.out.println("服务器异常" + statusCode);
}
httpClient.close();
}
}
工具类
package com.kaishengit.util;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class HttpUtil {
public static String sendHttpGetRequestWithString(String url) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = httpClient.execute(httpGet);
InputStream inputStream = null;
if (response.getStatusLine().getStatusCode() == 200) {
inputStream = response.getEntity().getContent();
String result = IOUtils.toString(inputStream,"UTF-8");
httpClient.close();
return result;
} else {
throw new RuntimeException("请求" + url + "异常 : " + response.getStatusLine().getStatusCode());
}
} catch (IOException ex) {
throw new RuntimeException("请求" + url + "异常",ex);
}
}
}
目前,要为另一个项目提供接口,接口是用HTTP URL实现的,最初的想法是另一个项目用jQuery post进行请求。
但是,很可能另一个项目是部署在别的机器上,那么就存在跨域问题,而jquery的post请求是不允许跨域的。
这时,就只能够用HttpClient包进行请求了,同时由于请求的URL是HTTPS的,为了避免需要证书,所以用一个类继承DefaultHttpClient类,忽略校验过程。
1.写一个SSLClient类,继承至HttpClient
package com.wanggs.httpclient;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
/**
* Created by wanggs on 2017/7/28.
* 用于进行Https请求的HttpClient
*/
public class SSLClient extends DefaultHttpClient {
public SSLClient() throws Exception {
super();
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx.init(null, new TrustManager[]{tm}, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = this.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", 443, ssf));
}
}
package com.wanggs.httpclient;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
/**
* Created by wanggs on 2017/7/28.
*/
public class HttpClientUtil {
public String doPost(String url,Map<String,String> map,String charset){
HttpClient httpClient = null;
HttpPost httpPost = null;
String result = null;
try{
httpClient = new SSLClient();
httpPost = new HttpPost(url);
//设置参数
List<NameValuePair> list = new ArrayList<NameValuePair>();
Iterator iterator = map.entrySet().iterator();
while(iterator.hasNext()){
Entry<String,String> elem = (Entry<String, String>) iterator.next();
list.add(new BasicNameValuePair(elem.getKey(),elem.getValue()));
}
if(list.size() > 0){
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,charset);
httpPost.setEntity(entity);
}
HttpResponse response = httpClient.execute(httpPost);
if(response != null){
HttpEntity resEntity = response.getEntity();
if(resEntity != null){
result = EntityUtils.toString(resEntity,charset);
}
}
}catch(Exception ex){
ex.printStackTrace();
}
return result;
}
}
测试
package com.wanggs.httpclient;
import java.util.HashMap;
import java.util.Map;
/**
* Created by wanggs on 2017/7/28.
*/
public class TestMain {
private String url = "http://www.pingwest.com/feed/";
private String charset = "utf-8";
private HttpClientUtil httpClientUtil = null;
public TestMain(){
httpClientUtil = new HttpClientUtil();
}
public void test(){
String httpOrgCreateTest = url + "httpOrg/create";
Map<String,String> createMap = new HashMap<String,String>();
createMap.put("authuser","*****");
createMap.put("authpass","*****");
createMap.put("orgkey","****");
createMap.put("orgname","****");
String httpOrgCreateTestRtn = httpClientUtil.doPost(httpOrgCreateTest,createMap,charset);
System.out.println("result:"+httpOrgCreateTestRtn);
}
public static void main(String[] args){
TestMain main = new TestMain();
main.test();
}
}