调用

doPost:map传参

Map<String,Object> map = new HashMap<>();
map.put("test","test");
String result = HttpClientUtils.getInstance().doPost(url, null, map);
    //被调用的方法
@PostMapping("/test")
@ApiOperation("测试")
@ResponseBody
public String test(@RequestBody String requestBody){
return testService.test(requestBody);
}
//取值
String test1= requestBody.split("&")[0].split("=")[1];
String test2= requestBody.split("&")[1].split("=")[1];

  

doPost:JSON传参(参数含中文使用JSON传参否则乱码)获得返回值

//JSON传参获得返回值
String errmsg = HttpClientUtils.getInstance().doPostWithJson(url,json.toJSONString());
//被调用的方法
@PostMapping("/test")
@ApiOperation("测试")
@ResponseBody
public String test(@RequestBody String template){
return testService.test(template);
}
//取值为JSON格式
JSONObject templateDTO = JSONObject.parseObject(template);
//进行自己的业务操作
return "";

工具类

package com.fxkj.common.util;

import com.alibaba.fastjson.JSONObject;
import com.fxkj.common.exception.BusinessException;
import com.fxkj.common.result.QCodeResult;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
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.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils; import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry; /**
* 分装一个http请求的工具类
*/
public class HttpClientUtils { private static HttpClientUtils instance;
CloseHttpUtil closeHttpUtil = new CloseHttpUtil();
private HttpClientUtils() {
}
public static synchronized HttpClientUtils getInstance() {
if (instance == null) {
instance = new HttpClientUtils();
}
return instance;
} /**
* <p>发送GET请求
*
* @param url GET请求地址(带参数)
* @param headerMap GET请求头参数容器
* @return 与当前请求对应的响应内容字
*/
public String doGet(String url, Map<String, Object> headerMap) {
String content = null;
CloseableHttpClient httpClient = getHttpClient();
try {
HttpGet getMethod = new HttpGet(url);
//头部请求信息
if (headerMap != null) {
Iterator iterator = headerMap.entrySet().iterator();
while (iterator.hasNext()) {
Entry entry = (Entry) iterator.next();
getMethod.addHeader(entry.getKey().toString(), entry.getValue().toString());
}
}
//发送get请求
CloseableHttpResponse httpResponse = httpClient.execute(getMethod);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
try {
//读取内容
content = EntityUtils.toString(httpResponse.getEntity());
} finally {
httpResponse.close();
}
} else {
throw new BusinessException(httpResponse.getStatusLine().getReasonPhrase());
}
} catch (IOException ex) {
throw new BusinessException(ex.getMessage());
} finally {
try {
closeHttpClient(httpClient);
} catch (Exception e) {
throw new BusinessException(e.getMessage());
}
}
return content;
} public String doGetRequest(String url, Map<String, String> headMap, Map<String, String> paramMap) {
// 获取连接客户端工具
CloseableHttpClient httpClient = HttpClients.createDefault();
String entityStr = null;
CloseableHttpResponse response = null;
try {
/*
* 由于GET请求的参数都是拼装在URL地址后方,所以我们要构建一个URL,带参数
*/
URIBuilder uriBuilder = new URIBuilder(url);
for (Entry<String, String> param : paramMap.entrySet()) {
uriBuilder.addParameter(param.getKey(), param.getValue());
}
// 根据带参数的URI对象构建GET请求对象
HttpGet httpGet = new HttpGet(uriBuilder.build()); /*
* 添加请求头信息
*/
if (null != headMap) {
for (Entry<String, String> header : headMap.entrySet()) {
httpGet.addHeader(header.getKey(), header.getValue());
}
}
/*httpGet.addHeader("Content-Type", "application/VIID+JSON;charset=utf8");
httpGet.addHeader("User-Identify","12345678905030000000");*/
closeHttpUtil.setTimeOut(httpGet);
// 执行请求
response = httpClient.execute(httpGet);
// 获得响应的实体对象
HttpEntity entity = response.getEntity();
// 使用Apache提供的工具类进行转换成字符串
entityStr = EntityUtils.toString(entity, "UTF-8");
} catch (ClientProtocolException e) {
System.err.println("Http协议出现问题");
e.printStackTrace();
} catch (ParseException e) {
System.err.println("解析错误");
e.printStackTrace();
} catch (URISyntaxException e) {
System.err.println("URI解析异常");
e.printStackTrace();
} catch (IOException e) {
System.err.println("IO异常");
e.printStackTrace();
} finally {
// 释放连接
closeHttpUtil.close(response, httpClient);
} return entityStr;
} /**
* <p>发送POST请求
*
* @param url POST请求地址
* @param headerMap POST请求头参数容器
* @param parameterMap POST请求参数容器
* @return 与当前请求对应的响应内容字
*/
public String doPost(String url, Map<String, Object> headerMap, Map<String, Object> parameterMap) {
String content = null;
CloseableHttpClient httpClient = getHttpClient();
try {
HttpPost postMethod = new HttpPost(url);
postMethod.setHeader("Content-Type", "application/json;charset=utf-8");
postMethod.setHeader("Accept", "application/json;charset=utf-8");
//头部请求信息
if (headerMap != null) {
Iterator iterator = headerMap.entrySet().iterator();
while (iterator.hasNext()) {
Entry entry = (Entry) iterator.next();
postMethod.addHeader(entry.getKey().toString(), entry.getValue().toString());
}
}
if (parameterMap != null) {
Iterator iterator = parameterMap.keySet().iterator();
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
while (iterator.hasNext()) {
String key = (String) iterator.next();
nvps.add(new BasicNameValuePair(key, String.valueOf(parameterMap.get(key))));
}
postMethod.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
} CloseableHttpResponse httpResponse = httpClient.execute(postMethod);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
try {
//读取内容
content = EntityUtils.toString(httpResponse.getEntity());
} finally {
httpResponse.close();
}
} else {
throw new BusinessException(httpResponse.getStatusLine().getReasonPhrase());
}
} catch (IOException ex) {
throw new BusinessException(ex.getMessage());
} finally {
try {
closeHttpClient(httpClient);
} catch (Exception e) {
throw new BusinessException(e.getMessage());
}
}
return content;
} public static String doPostWithJson(String url, String json) {
String returnValue = JsonUtils.write(QCodeResult.fail("接口异常!"));
CloseableHttpClient httpClient = HttpClients.createDefault();
ResponseHandler<String> responseHandler = new BasicResponseHandler();
try {
//第一步:创建HttpClient对象
httpClient = HttpClients.createDefault(); //第二步:创建httpPost对象
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(30000)
.setSocketTimeout(30000).setConnectTimeout(10000).build();
//第三步:给httpPost设置JSON格式的参数
StringEntity requestEntity = new StringEntity(json, "utf-8");
requestEntity.setContentEncoding("UTF-8");
httpPost.setHeader("Content-type", "application/json");
httpPost.setEntity(requestEntity);
httpPost.setConfig(requestConfig); //第四步:发送HttpPost请求,获取返回值
returnValue = httpClient.execute(httpPost, responseHandler); //调接口获取返回值时,必须用此方法
// System.out.println("请求返回:" + returnValue);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//第五步:处理返回值
return returnValue;
} public CloseableHttpClient getHttpClient() {
return HttpClients.createDefault();
} private void closeHttpClient(CloseableHttpClient client) throws IOException {
if (client != null) {
client.close();
}
} public static void get(String url) {
HttpGet request = new HttpGet(url);
try {
HttpResponse response = HttpClients.createDefault().execute(request);
if (response.getStatusLine().getStatusCode() == 200) {
EntityUtils.toString(response.getEntity());
}
} catch (Exception e) { }
}
}

  

HttpClient调用doGet、doPost、JSON传参及获得返回值的更多相关文章

  1. C# 多线程编程,传参,接受返回值

    C# 多线程编程,传参,接受返回值 今天将多线程的知识有回顾了下,总结了几点: 新建一个线程(无参数,无返回值) Thread th = new Thread(new ThreadStart(Prin ...

  2. Java调用动态链接库so文件(传参以及处理返回值问题)

    刚来到公司,屁股还没坐稳,老板把我叫到办公室,就让我做一个小程序.我瞬间懵逼了.对小程序一窍不通,还好通过学习小程序视频,两天的时间就做了一个云开发的小程序,但是领导不想核心的代码被别人看到,给了我一 ...

  3. HttpClient 调用WebAPI时,传参的三种方式

    public void Post() { //方法一,传json参数 var d = new { username = " ", password = " ", ...

  4. C#打开php链接传参然后接收返回值

    php代码 一.php <?php header("Content-Type:text/html;charset=UTF-8"); $u=$_POST['zdupdate'] ...

  5. json传参应用

    json传参应用 JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式.JSON采用完全独立于语言的文本格式,这些特性使JSON成为理想的数据交换语言.易于人阅 ...

  6. ASP.NET WebAPI RC 竟然不支持最常用的json传参

    壮士断腕(WCF Web API),为的是 ASP.NET Web API 的横空出世,再加上它的开放(开源),于是对之产生了一点点痴情,并写下了HttpClient + ASP.NET Web AP ...

  7. SpringBoot 处理 POST Json 传参枚举

    在 Spring 框架中对枚举类型的序列化/反序列化是有限制的. 假设如下面这样在某些情况下就不能正常工作: 123456789 public enum PayChannelEnum implemen ...

  8. asp.net 通过ajax方式调用webmethod方法使用自定义类传参及获取返回参数

    实体类    public class User    {        public int Id { get; set; }        public string Name { get; se ...

  9. json传参 js前端和java后端 的简单例子

    下面讲解了从前端js对象-->json字符串-->java字符串---->java map的过程 1,初始化js对象 var param = {}; param.krel = kre ...

随机推荐

  1. XCTF Normal_RSA

    这题本来算是很常规的rsa了,下载附件 发现有个公钥文件,还有一个加密文件,这种题之前有遇到一次,做法和这个类似,上次那个是用rsa的库,直接解的,这次直接用常规的,好像更简单,记录下模板 记事本打开 ...

  2. B 站崩了,总结下「高可用」和「异地多活」

    你好,我是悟空. 一.背景 不用想象一种异常场景了,这就真实发生了:B 站晚上 11 点突然挂了,网站主页直接报 404. 手机 APP 端数据加载不出来. 23:30 分,B 站做了降级页面,将 4 ...

  3. C# 8.0和.NET Core 3.0高级编程 分享笔记三:控制流程和转换类型

    控制流程和转换类型 本章的内容主要包括编写代码.对变量执行简单的操作.做出决策.重复执行语句块.将变量或表达式值从一种类型转换为另一种类型.处理异常以及在数值变量中检查溢出. 本章涵盖以下主题: 操作 ...

  4. linux挂载光驱

    挂载光驱到linux中.linux的镜像盘中有安装oracle的所有的软件包,可以会用yum一键安装. 1.此时的linux的界面显示光驱图标 2.挂载 因为光盘里面的文件是只读模式的,yum安装时不 ...

  5. CTF-Decrypt-the-Message-writeup

    Decrypt-the-Message 题目信息: 解密这段信息! 附件: The life that I have Is all that I have And the life that I ha ...

  6. Quick BI的复杂系统为例:那些年,我们一起做过的性能优化

    背景 一直以来,性能都是技术层面不可避开的话题,尤其在中大型复杂项目中.犹如汽车整车性能,追求极速的同时,还要保障舒适性和实用性,而在汽车制造的每个环节.零件整合情况.发动机调校等等,都会最终影响用户 ...

  7. java并发编程基础——线程通信

    线程通信 当线程在系统内运行时,程序通常无法准确的控制线程的轮换执行,但我们可以通过一些机制来保障线程的协调运行 一.传统的线程通信 传统的线程通信主要是通过Object类提供的wait(),noti ...

  8. C++之vector容器

    一.STL的基本概念 STL(Standard Template Library)标准模板库大体上分为六大组件,分别为容器,算法,迭代器,仿函数,适配器和空间配置器,其中最重要的是容器,算法和迭代器, ...

  9. C#曲线分析平台的制作(四,highcharts+ajax加载后台数据)

    在上一篇博客:C#曲线分析平台的制作(三,三层构架+echarts显示)中已经完成了后台的三层构架的简单搭建,为实现后面的拓展应用开发和review 改写提供了方便.而在曲线分析平台中,往往有要求时间 ...

  10. JMeter Gui – TestElement约定[转]

    转自https://www.cnblogs.com/yigui/p/7615635.html 在编写任何JMeter组件时,必须注意某些特定的约定--如果JMeter环境中正确地运行JMeter组件, ...