现在的接口开发,大部分是基于http的请求和处理,现在整理了一份常用的调用方式工具类

package com.xh.oms.common.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; import net.sf.json.JSONObject; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils; public class HttpClientUtil { /**
* 发送post请求,json格式数据
* @param url
* @param params
* @return
*/
public static JSONObject postJsonData(String url,Map<String,String> params){
CloseableHttpClient httpclient = HttpClientUtil.createDefault();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Authorization", "your token"); //认证token
httpPost.addHeader("Content-type","application/json; charset=utf-8");
httpPost.addHeader("User-Agent", "imgfornote");
httpPost.setHeader("Accept", "application/json"); //拼接参数
JSONObject jsonParams = new JSONObject();
for (Map.Entry<String, String> entry : params.entrySet()) {
String key = entry.getKey().toString();
String value = entry.getValue().toString();
jsonParams.put(key, value);
} //配置请求超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(1*60*1000) //设置连接超时时间,单位毫秒
// .setConnectionRequestTimeout(1000) //设置从connect Manager获取Connection 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
.setSocketTimeout(3*60*1000).build(); //请求获取数据的超时时间,单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
httpPost.setConfig(requestConfig); CloseableHttpResponse response=null;
try {
httpPost.setEntity(new StringEntity(jsonParams.toString(), Charset.forName("UTF-8")));
response = httpclient.execute(httpPost);
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} /**请求发送成功,并得到响应**/
JSONObject jsonObject=null;
if(response != null){
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
HttpEntity httpEntity = response.getEntity();
String result=null;
try {
result = EntityUtils.toString(httpEntity);
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 返回json格式:
jsonObject = JSONObject.fromObject(result);
}
} return jsonObject;
} /**
* 发送post请求
* @param url
* @param params
* @return
*/
public static JSONObject postData(String url,Map<String,String> params){
CloseableHttpClient httpclient = HttpClientUtil.createDefault();
HttpPost httpPost = new HttpPost(url); //拼接参数
List<NameValuePair> list = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : params.entrySet()) {
String key = entry.getKey().toString();
String value = entry.getValue().toString();
NameValuePair pair = new BasicNameValuePair(key, value);
list.add(pair);
} CloseableHttpResponse response=null;
try {
httpPost.setEntity(new UrlEncodedFormEntity(list,"UTF-8"));
response = httpclient.execute(httpPost);
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} /**请求发送成功,并得到响应**/
JSONObject jsonObject=null;
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
HttpEntity httpEntity = response.getEntity();
String result=null;
try {
result = EntityUtils.toString(httpEntity);
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 返回json格式:
jsonObject = JSONObject.fromObject(result);
}
return jsonObject;
} /**
* 向指定URL发送GET方法的请求
*
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return URL 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
} /**
* get请求
* @param url
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return
*/
public static JSONObject httpGet(String url, String param){
JSONObject jsonResult = null; //get请求返回结果
try { CloseableHttpClient httpclient = HttpClientUtil.createDefault();
//发送get请求
HttpGet request = new HttpGet(url);
URI realUrl = new URI(url + "?" + param);
request.setURI(realUrl);
HttpResponse response = httpclient.execute(request); /**请求发送成功,并得到响应**/
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { /**读取服务器返回过来的json字符串数据**/
String strResult = EntityUtils.toString(response.getEntity()); /**把json字符串转换成json对象**/
jsonResult = JSONObject.fromObject(strResult);
url = URLDecoder.decode(url, "UTF-8");
} else {
System.out.println("get请求提交失败:" + url);
}
} catch (IOException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
return jsonResult;
} /**
* Creates {@link CloseableHttpClient} instance with default
* configuration.
*/
public static CloseableHttpClient createDefault() {
return HttpClientBuilder.create().build();
} }

  

基于apache httpclient的常用接口调用方法的更多相关文章

  1. phpcms常用接口调用方法

    常用函数 , 打开include/global.func.php,下面存放一些公共函数 view plaincopy to clipboardprint?function str_charset($i ...

  2. (转)Arcgis API常用接口调用方法

    var map, navToolbar, editToolbar, tileLayer, toolbar;//var mapBaseUrl = "http://localhost:8399/ ...

  3. SERVLET类常用接口及方法

    SERVLET类常用接口及方法 2011-09-09 16:14:43    [size=xx-small]SERVLET类常用接口及方法2007年04月05日 星期四 04:46 P.M.基本类和接 ...

  4. 基于apache httpclient 调用Face++ API

    简要: 本文简要介绍使用Apache HttpClient工具调用旷世科技的Face API. 前期准备: 依赖包maven地址: <!-- https://mvnrepository.com/ ...

  5. 云极知客开放平台接口调用方法(C#)

    云极知客为企业提供基于SAAS的智能问答服务.支持企业个性化知识库的快速导入,借助语义模型的理解和分析,使企业客户立即就拥有本行业的24小时客服小专家.其SAAS模式实现零成本投入下的实时客服数据的可 ...

  6. 基于JAVA的全国天气预报接口调用示例

    step1:选择本文所示例的接口"全国天气预报接口" url:https://www.juhe.cn/docs/api/id/39/aid/87step2:每个接口都需要传入一个参 ...

  7. 新浪网易淘宝等IP地区信息查询开放API接口调用方法

    通过IP地址获取对应的地区信息通常有两种方法:1)自己写程序,解析IP对应的地区信息,需要数据库.2)根据第三方提供的API查询获取地区信息. 第一种方法,参见文本<通过纯真IP数据库获取IP地 ...

  8. DEDE 常用的调用方法

    DEDE织梦常用的调用常规调用: 网站名称调用:<title>{dede:global.cfg_webname/}</title> 网站关键词调用:<meta name= ...

  9. DEDE织梦常用的调用方法

    DEDE织梦常用的调用常规调用: 网站名称调用:<title>{dede:global.cfg_webname/}</title> 网站关键词调用:<meta name= ...

随机推荐

  1. logback备注

    <?xmlversion="1.0"encoding="UTF-8"?> <!-- <configuration>包含的属性 sc ...

  2. npm-install camo

    camo是针对Node.js和MongoDB的对象模型mapper(object document mapper)(ODM) 可以喝Mongoose ODM互换,但是和其有显著的不同 文章主要关注了M ...

  3. JSP常见知识点

    false 7.8 磅 0 2 false false false false EN-US ZH-CN X-NONE /* Style Definitions */ table.MsoNormalTa ...

  4. ***静态成员的定义及初始化 for c++ for新用法

    静态成员的初始化要在类外不然报错error: ISO C++ forbids in-class initialization of non-const static member '***' 但是声明 ...

  5. P2051 [AHOI2009]中国象棋[线性DP]

    最近智商有点不在线.其实一直不在线. 题目 先是想用$f[i][j][k][0/1/2]$表示摆了i行时有j列空着,k列有了一个炮,且当下摆了0/1/2个的状态,转移方程写的出来但是极其繁琐.于是又设 ...

  6. Python中定时任务框架APScheduler的快速入门指南

    前言 大家应该都知道在编程语言中,定时任务是常用的一种调度形式,在Python中也涌现了非常多的调度模块,本文将简要介绍APScheduler的基本使用方法. 一.APScheduler介绍 APSc ...

  7. bzoj 4275 Badania naukowe —— DP

    题目:https://www.lydsy.com/JudgeOnline/problem.php?id=4275 枚举 \( C \) 在 \( A \) 和 \( B \) 中的位置,然后取它前后的 ...

  8. bzoj4176

    莫比乌斯反演 根据约数和个数公式 $ans = \sum_{i=1}^{n}\sum_{j=1}^{n}\sum_{x|i}\sum_{y|j}{[gcd(i, j)==1]}$ 交换枚举顺序 $an ...

  9. AngularJs(Part 4)--Modules depending on other Modules

    Angular does an excellent job of managing object dependencies. it can even take care of module depen ...

  10. CentOS 下部署Nginx+Gunicorn+Supervisor部署Flask项目

    原本之前有一部分东西是在Windows Server,但是由于Gunicorn不支持Windows部署起来颇为麻烦.最近转战CentOS,折腾一段时间,终于简单部署成功.CentOS新手,作为一个总结 ...