当前位置: 首页 > news >正文

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);
// }
}


转载于:https://www.cnblogs.com/jianmianruxin/p/8325066.html

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 类的高级特性——抽象类
  • 微信文章编辑器
  • 分块算法
  • jQuery设置div的自适应布局
  • face alignment---各种算法框架
  • jQuery与vue分别实现超级简单的绿色拖动验证码功能
  • ShardingJDBC不支持批量插入的一种解决办法
  • NFS服务的端口分配
  • PHP中new self()和new static()的区别探究
  • rsync工具介绍
  • ubuntu配置虚拟主机
  • 客户端传输数据的方式
  • Django+Nginx+uwsgi搭建自己的博客(三)
  • turtlebot3_waffle 之PC工作环境搭建过程记录
  • Flask 安装 快速入门
  • 【划重点】MySQL技术内幕:InnoDB存储引擎
  • docker python 配置
  • Docker下部署自己的LNMP工作环境
  • Facebook AccountKit 接入的坑点
  • Hexo+码云+git快速搭建免费的静态Blog
  • Laravel深入学习6 - 应用体系结构:解耦事件处理器
  • react 代码优化(一) ——事件处理
  • 记一次和乔布斯合作最难忘的经历
  • 前嗅ForeSpider采集配置界面介绍
  • 如何在GitHub上创建个人博客
  • 思考 CSS 架构
  • 学习笔记TF060:图像语音结合,看图说话
  •  一套莫尔斯电报听写、翻译系统
  • ​浅谈 Linux 中的 core dump 分析方法
  • (2024.6.23)最新版MAVEN的安装和配置教程(超详细)
  • (35)远程识别(又称无人机识别)(二)
  • (poj1.3.2)1791(构造法模拟)
  • (安全基本功)磁盘MBR,分区表,活动分区,引导扇区。。。详解与区别
  • (二)【Jmeter】专栏实战项目靶场drupal部署
  • (二)原生js案例之数码时钟计时
  • (翻译)Quartz官方教程——第一课:Quartz入门
  • (教学思路 C#之类三)方法参数类型(ref、out、parmas)
  • (免费领源码)Python#MySQL图书馆管理系统071718-计算机毕业设计项目选题推荐
  • (十八)devops持续集成开发——使用docker安装部署jenkins流水线服务
  • (数据结构)顺序表的定义
  • (四)linux文件内容查看
  • (一)ClickHouse 中的 `MaterializedMySQL` 数据库引擎的使用方法、设置、特性和限制。
  • (转)scrum常见工具列表
  • (轉貼) 寄發紅帖基本原則(教育部禮儀司頒布) (雜項)
  • **PHP二维数组遍历时同时赋值
  • .NET 4 并行(多核)“.NET研究”编程系列之二 从Task开始
  • .net 写了一个支持重试、熔断和超时策略的 HttpClient 实例池
  • .NET/C# 利用 Walterlv.WeakEvents 高性能地中转一个自定义的弱事件(可让任意 CLR 事件成为弱事件)
  • .Net+SQL Server企业应用性能优化笔记4——精确查找瓶颈
  • .sdf和.msp文件读取
  • /tmp目录下出现system-private文件夹解决方法
  • @AutoConfigurationPackage的使用
  • @cacheable 是否缓存成功_让我们来学习学习SpringCache分布式缓存,为什么用?
  • @Value获取值和@ConfigurationProperties获取值用法及比较(springboot)
  • []指针