<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 {
// 創(chuàng)建了一個可以發(fā)出請求的客戶端
CloseableHttpClient httpClient = HttpClients.createDefault();
// 創(chuàng)建一個Get請求
HttpGet httpGet = new HttpGet("http://www.pingwest.com/feed/");
// HttpPost httpPost = new HttpPost("http://www.pingwest.com/feed/"); POST請求
// 發(fā)出請求,并接受服務(wù)端相應(yīng)
HttpResponse response = httpClient.execute(httpGet);
// 獲取Http狀態(tài)碼
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// html 也就是獲取相應(yīng)輸入流
InputStream inputStream = response.getEntity().getContent();
String result = IOUtils.toString(inputStream, "UTF-8");
inputStream.close();
System.out.println(result);
} else {
System.out.println("服務(wù)器異常" + 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實現(xiàn)的,最初的想法是另一個項目用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);
//設(shè)置參數(shù)
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();
}
}
image.png