现在的接口开发,大部分是基于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. 存储过程之ROWTYPE 使用事例

    CREATE OR REPLACE PROCEDURE "DYLTWZDSJ_CP_BA" (YWID IN VARCHAR2, XKZBH IN VARCHAR2, FLAG O ...

  2. Composer基础应用1

    先唠叨唠叨一些琐碎的事.本人最早从事.Net开发,后来处于好奇慢慢转到了php,因为.net从一早就使用了命名空间(反正从我使用就存在这玩意了),所以在转php时很自然的就使用了命名空间,但是在使用过 ...

  3. mysql 优化 实现命中率100%

    配置你的mysql配置文件:主要是配置[mysqld]后面的内容. 1,优化远程连接速度. 在[mysqld]下面添加skip-name-resolve skip-name-resolve 选项就能禁 ...

  4. Zabbix数据库清理历史数据

    Zabbix清理历史数据 Zabbix是个很好的监控软件,随着公司监控项目越来越多,数据越来越多,zabbix负载重,可能造成系统性能下降. Zabbix里面最大的表就是历史记录表,history,h ...

  5. Linux_异常_04_ftp: command not found...

    今天在centos上使用ftp命令连接本机的FTP服务器(本机FTP服务使用Vsftpd搭建),出现如下的错误提示:-bash: ftp: command not found 查询相关资料,发现很有可 ...

  6. Python: scikit-image 彩色图像滤波

    一般的滤波器都是针对灰度图像的,scikit-image 库提供了针对彩色图像滤波的decorator:adapt_rgb,adapt_rgb 提供两种形式的滤波,一种是对rgb三个通道分别进行处理, ...

  7. win10系统下安装64位Oracle11g+LSQL Developer

    LSQL Developer作为强大的Oracle编辑工具,却只支持32bit,本文提供在安装用LSQL Developer打开64bitOracle的操作方法 工具/原料  oracle11g安装包 ...

  8. Python3解leetcode Best Time to Buy and Sell Stock II

    问题描述: Say you have an array for which the ith element is the price of a given stock on day i. Design ...

  9. 整理出来的一个windows关机、锁定、重启、注销 API调用

    using System.Runtime.InteropServices; namespace HookDemo { class WindowsExit { [StructLayout(LayoutK ...

  10. 要把target下面虚拟路径的项目文件…

     源码进不去,要检查target下面的项目文件,要删除掉. 版权声明:本文为博主原创文章,未经博主允许不得转载.