HTTP请求(CloseableHttpClient是否就是HTTP协议规则的实现?)

Posted speak out now.

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HTTP请求(CloseableHttpClient是否就是HTTP协议规则的实现?)相关的知识,希望对你有一定的参考价值。

发起HTTP协议的交互请求:
想发起就能发起(符合万维网系统制定的HTTP协议即可,规定格式的请求头,请求体等),但能不能返回和返回什么由目标接口决定。如果返回有问题,生成的状态码是万维网系统检测并返回吗?为什么后台开发者也能设定状态码?

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class HttpClientUtil {

/**
* 发送http get 请求
* @param url url
* @return 响应体字符串
* @throws IOException IOException
*/
public static String httpGet(String url) throws IOException {

String responseStr;

CloseableHttpClient httpClient = createSSLClientDefault();

HttpGet httpget = new HttpGet(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(45000).build();
httpget.setConfig(requestConfig);

ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

@Override
public String handleResponse(final HttpResponse response) throws IOException {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
} else {
throw new ClientProtocolException("Unexpected message status: " + status);
}
}

};

responseStr = httpClient.execute(httpget, responseHandler);

return responseStr;
}

/**
* 发送http post 请求
* @param url url
* @return 响应体字符串
* @throws IOException IOException
*/
public static String httpPost(String url, String body) throws IOException {

String responseStr;

CloseableHttpClient httpClient = createSSLClientDefault();

HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type", "application/json");

RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(45000).build();
httpPost.setConfig(requestConfig);

HttpEntity entity = new ByteArrayEntity(body.getBytes("utf-8"));
httpPost.setEntity(entity);

ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

@Override
public String handleResponse(final HttpResponse response) throws IOException {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
} else {
throw new ClientProtocolException("Unexpected message status: " + status);
}
}

};

responseStr = httpClient.execute(httpPost, responseHandler);

return responseStr;
}

/**
* 创建可以发送https请求的httpclient
* @return CloseableHttpClient
*/
private static CloseableHttpClient createSSLClientDefault() {
try {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
// 信任所有
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new MyHostnameVerifier());
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
e.printStackTrace();
}
return HttpClients.createDefault();
}

// SSLPeerUnverifiedException: Host name err
private static class MyHostnameVerifier implements HostnameVerifier {
@Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}

}

}


以上是关于HTTP请求(CloseableHttpClient是否就是HTTP协议规则的实现?)的主要内容,如果未能解决你的问题,请参考以下文章

HTTP协议HTTP请求和响应

HTTP请求方法

HTTP协议:HTTP请求和相关API

HTTP请求行、请求头、请求体详解

Spring HTTP请求过程

HTTP请求报文结构