Apache HttpClient使用
来源:互联网 发布:电信4g网络apn设置 编辑:程序博客网 时间:2024/06/07 06:47
一 场景:
java后台开发经常会需要发送HTTP请求,经常会使用Apache的HttpClient发送请求。
二 Post发送表单
1.设置请求参数
List<BasicNameValuePair> content = new ArrayList<BasicNameValuePair>();content.add(new BasicNameValuePair("tradingPartner", "jaden");content.add(new BasicNameValuePair("documentProtocol", "jaden"));content.add(new BasicNameValuePair("requestMessage", sw.toString()));//调用Http请求方法String result = sentHttpPostRequest(url, content);
2.发送HTTP请求
public String sentHttpPostRequest(String url, List<BasicNameValuePair> content) throws Exception { //构建HttpClient实例 CloseableHttpClient httpclient = HttpClients.createDefault(); //设置请求超时时间 RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(60000) .setConnectTimeout(60000) .setConnectionRequestTimeout(60000) .build(); //指定POST请求 HttpPost httppost = new HttpPost(url); httppost.setConfig(requestConfig); //包装请求体 List<NameValuePair> params = new ArrayList<NameValuePair>(); params.addAll(content); HttpEntity request = new UrlEncodedFormEntity(params, "utf-8"); //发送请求 httppost.setEntity(request); CloseableHttpResponse httpResponse = httpclient.execute(httppost); //读取响应 HttpEntity entity = httpResponse.getEntity(); String result = null; if (entity != null) { result = EntityUtils.toString(entity); } return result; }
说明:
1.创建可关闭的HttpClient,即 CloseableHttpClient httpclient;
2.读取响应,也是用可关闭的response,即CloseableHttpResponse httpResponse;
好处:这样可以使得创建出来的HTTP实体,可以被Java虚拟机回收掉,不至于出现一直占用资源的情况。
三 Post发送JSON字符串
大部分同上述代码相同,不同之处在于包装请求体部分:
String jsonStr = {"name":"jaden","age":"23","other":"xxx"};HttpEntity param = new StringEntity(jsonStr, "UTF-8");//设置请求体httppost.setEntity(param);
四 Get请求
使用HttpGet即可
CloseableHttpClient httpclient = HttpClients.createDefault();HttpGet request = new HttpGet(url);request.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) ...");CloseableHttpResponse response = httpclient.execute(request);// read response
日常总结,助人助己。
阅读全文
1 0
- 使用Apache httpclient
- apache httpclient 使用例子
- Apache HttpClient 使用
- apache HttpClient使用详解
- 使用 Apache HttpClient
- Apache HttpClient使用详解
- apache HttpClient的使用
- Apache HttpClient使用
- org.apache.commons.httpclient.HttpClient的使用
- org.apache.commons.httpclient.HttpClient的使用
- Android 6.0 使用 Apache HttpClient
- Android 6.0 使用 Apache HttpClient
- Android 6.0 使用 Apache HttpClient
- Android 6.0 使用 Apache HttpClient
- Android 6.0 使用 Apache HttpClient
- Android 6.0 使用 Apache HttpClient
- Android 6.0 使用 Apache HttpClient
- Android中使用Apache HttpClient
- (转)Activity返回(finish)时,另一个activity或者fragment如何刷新数据
- JAVA基础——初识JAVA(四)(Scanner、算术、赋值、比较、逻辑、三元运算符)
- python day3 总结
- 比特币延展性攻击
- 使QLabel上显示的图片大小和QLabel自适应
- Apache HttpClient使用
- 计算1-1/2+1/3-1/4+...+1/n的两种方法
- 批量执行redis命令行(windows)
- Chrome浏览器跨域设置
- unbuntu vim 配置
- <Android> 文件夹和文件操作
- (ssl1125) 集合(normal)
- 关于jquery checkbox的一点问题
- 用c++实现推箱子