import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.net.ssl.SSLContext;
import org.apache.http.HttpEntity;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
/**
* http://hc.apache.org/httpcomponents-client-ga/tutorial/html/
* @author Administrator
*
*/
public class TestHttpClient {
/**
* Get请求
*/
@Test
public void test1(){
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet get = new HttpGet("http://www.baidu.com");
CloseableHttpResponse response = httpClient.execute(get);
response.getEntity().writeTo(System.out);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Post请求
*/
@Test
public void test2(){
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
formParams.add(new BasicNameValuePair("param1", "value1"));
formParams.add(new BasicNameValuePair("param2", "value2"));
HttpPost post = new HttpPost("");
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams);
post.setEntity(entity);
CloseableHttpResponse respones = httpClient.execute(post);
EntityUtils.toString(respones.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static PoolingHttpClientConnectionManager clientConnectionManager=null;
private static CloseableHttpClient httpClient=null;
private static RequestConfig config = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).build();
private final static Object syncLock = new Object();
static {
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("https", SSLConnectionSocketFactory.getSocketFactory())
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.build();
clientConnectionManager =new PoolingHttpClientConnectionManager(socketFactoryRegistry);
clientConnectionManager.setMaxTotal(50);
clientConnectionManager.setDefaultMaxPerRoute(25);
}
public static CloseableHttpClient getHttpClient(){
if(httpClient == null){
synchronized (syncLock){
if(httpClient == null){
BasicCookieStore cookieStore = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("sessionID", "######");
cookie.setDomain("#####");
cookie.setPath("/");
cookieStore.addCookie(cookie);
httpClient =HttpClients.custom().setConnectionManager(clientConnectionManager).setDefaultCookieStore(cookieStore).setDefaultRequestConfig(config).build();
}
}
}
return httpClient;
}
public static HttpEntity httpGet(String url, Map<String,Object> headers){
CloseableHttpClient httpClient = getHttpClient();
HttpRequest httpGet = new HttpGet(url);
if(headers!=null&&!headers.isEmpty()){
httpGet = setHeaders(headers, httpGet);
}
CloseableHttpResponse response = null;
try{
response =httpClient.execute((HttpGet)httpGet);
HttpEntity entity = response.getEntity();
return entity;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
/**
使用表单键值对传参
*/
public static HttpEntity httpPost(String url,Map<String,Object> headers,List<NameValuePair> data){
CloseableHttpClient httpClient = getHttpClient();
HttpRequest request = new HttpPost(url);
if(headers!=null&&!headers.isEmpty()){
request = setHeaders(headers,request);
}
CloseableHttpResponse response = null;
UrlEncodedFormEntity uefEntity;
try {
HttpPost httpPost = (HttpPost) request;
uefEntity = new UrlEncodedFormEntity(data,"UTF-8");
httpPost.setEntity(uefEntity);
// httpPost.setEntity(new StringEntity(data, ContentType.create("application/json", "UTF-8")));
response=httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
return entity;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 设置请求头信息
* @param headers
* @param request
* @return
*/
private static HttpRequest setHeaders(Map<String,Object> headers, HttpRequest request) {
for (Map.Entry entry : headers.entrySet()) {
if (!entry.getKey().equals("Cookie")) {
request.addHeader((String) entry.getKey(), (String) entry.getValue());
} else {
Map<String, Object> Cookies = (Map<String, Object>) entry.getValue();
for (Map.Entry entry1 : Cookies.entrySet()) {
request.addHeader(new BasicHeader("Cookie", (String) entry1.getValue()));
}
}
}
return request;
}
public static void main(String[] args) {
try {
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
InputStream instream = new FileInputStream("D:/a.keystore");
keyStore.load(instream, "123456".toCharArray());
instream.close();
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(keyStore, new TrustSelfSignedStrategy()).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
/* List<NameValuePair> formParams = new ArrayList<NameValuePair>();
formParams.add(new BasicNameValuePair("username", "test"));
HttpPost post = new HttpPost("https://localhost:8443/servlet/servlet/LoginServlet");
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams);
post.setEntity(entity);
CloseableHttpResponse respones = httpClient.execute(post);
EntityUtils.toString(respones.getEntity());*/
HttpPost request = new HttpPost("https://localhost:8443/servlet/servlet/LoginServlet");
List<BasicNameValuePair> formParams = new ArrayList<BasicNameValuePair>();
formParams.add(new BasicNameValuePair("username", "中国"));
HttpEntity entity = new UrlEncodedFormEntity(formParams, "UTF-8");
request.setEntity(entity);
HttpResponse response = httpClient.execute(request);
// 打印请求信息
System.out.println(request.getRequestLine());
// 打印响应信息
System.out.println(response.getStatusLine());
response.getEntity().writeTo(System.out);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
}
}
apache HttpClient的使用
最新推荐文章于 2024-08-15 22:28:28 发布