• 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;
    }

    }

    }









    trade

    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.util.Map;

    import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.HttpStatus;
    import org.apache.commons.httpclient.NameValuePair;
    import org.apache.commons.httpclient.methods.PostMethod;
    import org.apache.commons.httpclient.params.HttpMethodParams;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;

    import com.jd.ihtrade.core.constant.HttpResponseResult;
    import com.jd.ihtrade.core.constant.PopRefundConstants;




    /**
    * @author panyujiang
    * @date 2016-06-01
    * @desc http通讯Util工具类
    */
    public class HttpClientUtil {

    private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);


    /**
    * 如果成功返回就code=0;BODY为返回内容,如果code!=0 errMsg为错误内容
    * @param url 地址
    * @param parameters 参数
    * @return
    */
    public static HttpResponseResult request(String url, Map<String, String> parameters) {
    HttpResponseResult responseResult = new HttpResponseResult();
    StringBuffer response = new StringBuffer();

    //设置HTTP请求参数
    HttpClient client = new HttpClient();
    client.getParams().setConnectionManagerTimeout(PopRefundConstants.CONNECT_TIMEOUT);
    PostMethod method = new PostMethod(url);

    method.getParams().setContentCharset(PopRefundConstants.CHARSET_GBK);
    method.getParams().setSoTimeout(PopRefundConstants.GET_DATA_TIMEOUT);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
    new DefaultHttpMethodRetryHandler(PopRefundConstants.RETRY_COUNT, false));

    try {
    if (parameters != null && parameters.isEmpty() == false) {
    NameValuePair[] postData = new NameValuePair[parameters.size()];
    int i = 0;
    for (Map.Entry<String, String> entry : parameters.entrySet()) {
    postData[i++] = new NameValuePair(entry.getKey(), entry.getValue());
    }
    method.setRequestBody(postData);
    }
    client.executeMethod(method);
    responseResult.setCode(method.getStatusCode());
    BufferedReader reader = null;
    try {
    reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), PopRefundConstants.CHARSET_GBK));
    String line;
    while ((line = reader.readLine()) != null) {
    response.append(line);
    }

    } catch (Exception e) {
    logger.error("request", e);
    throw new RuntimeException(e);

    } finally {
    if (reader != null) {
    reader.close();
    }
    }
    //返回状态码错误
    if (method.getStatusCode() != HttpStatus.SC_OK) {
    responseResult.setErrMsg(response.toString());

    } else {
    responseResult.setCode(PopRefundConstants.RESULT_SUCCESS);//把200转为RESULT_SUCCESS
    responseResult.setBody(response.toString());
    }

    } catch (Exception e) {
    responseResult.setCode(PopRefundConstants.RESULT_FAILURE);
    responseResult.setErrMsg("error:" + e.getMessage());
    logger.error("request", e);
    } finally {
    method.releaseConnection();
    }
    return responseResult;
    }


    public static HttpResponseResult requestData(String url, String data) {
    HttpResponseResult responseResult = new HttpResponseResult();
    StringBuffer response = new StringBuffer();

    //设置HTTP请求参数
    HttpClient client = new HttpClient();
    client.getParams().setConnectionManagerTimeout(PopRefundConstants.CONNECT_TIMEOUT);
    PostMethod method = new PostMethod(url);

    method.getParams().setContentCharset(PopRefundConstants.CHARSET_UTF_8);
    method.getParams().setSoTimeout(PopRefundConstants.GET_DATA_TIMEOUT);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
    new DefaultHttpMethodRetryHandler(PopRefundConstants.RETRY_COUNT, false));

    try {
    // if (parameters != null && parameters.isEmpty() == false) {
    // NameValuePair[] postData = new NameValuePair[parameters.size()];
    // int i = 0;
    // for (Map.Entry<String, String> entry : parameters.entrySet()) {
    // postData[i++] = new NameValuePair(entry.getKey(), entry.getValue());
    // }
    // method.setRequestBody(postData);
    // }
    method.setRequestBody(data);
    client.executeMethod(method);
    responseResult.setCode(method.getStatusCode());
    BufferedReader reader = null;
    try {
    reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), PopRefundConstants.CHARSET_UTF_8));
    String line;
    while ((line = reader.readLine()) != null) {
    response.append(line);
    }

    } catch (Exception e) {
    logger.error("request", e);
    throw new RuntimeException(e);

    } finally {
    if (reader != null) {
    reader.close();
    }
    }
    //返回状态码错误
    if (method.getStatusCode() != HttpStatus.SC_OK) {
    responseResult.setErrMsg(response.toString());

    } else {
    responseResult.setCode(PopRefundConstants.RESULT_SUCCESS);//把200转为RESULT_SUCCESS
    responseResult.setBody(response.toString());
    }

    } catch (Exception e) {
    responseResult.setCode(PopRefundConstants.RESULT_FAILURE);
    responseResult.setErrMsg("error:" + e.getMessage());
    logger.error("request", e);
    } finally {
    method.releaseConnection();
    }
    return responseResult;
    }

    // public static void main(String[] args) {
    // String url = "http://wkws.dhc.jd.com/service1/lasRestService/queryOrderStatus2";
    // String data = "<?xml version="1.0" encoding="utf-8" ?>" + "<data>" + "<order>" + "<waybill_code>170327117</waybill_code>" + "</order>"
    // + "</data>";
    // String contentType = "application/soap+xml";
    // String result = post(url, data, contentType);
    // System.out.println(result);
    // }
    }


    新生的小心情
  • 相关阅读:
    Mac上的抓包工具Charles[转载]
    js 实现自动调出键盘
    Mac下git安装(使用Xcode)
    weinre远程调试
    Css Sprite Demo
    sublime 常用快捷键
    css 盒子模型 以及 box-sizing属性
    jquery中bind,live,delegate,on的区别
    模拟实现库函数的atoi、atof和itoa
    常见排序算法
  • 原文地址:https://www.cnblogs.com/jianmianruxin/p/8325066.html
Copyright © 2020-2023  润新知