httpClient请求接口,用httpEntity接受结果
标题
包含get和post的有参和无参的请求
post有参请求用httpEntity接受,处理成JsonObject类型
方法
package com.shzu.xyf.finding_sql_install_system.finding_sql_install_system.common;import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;public class HttpClientUtils {// 无参数的Get请求public static HttpEntity getWithoutParams(String url) {CloseableHttpClient httpClient = HttpClientBuilder.create().build();// 创建Get请求HttpGet httpGet = new HttpGet(url);// 响应模型CloseableHttpResponse response = null;try {// 由客户端执行(发送)Get请求response = httpClient.execute(httpGet);// 从响应模型中获取响应实体HttpEntity responseEntity = response.getEntity();System.out.println("响应状态为:" + response.getStatusLine());if (responseEntity != null) {System.out.println("响应内容长度为:" + responseEntity.getContentLength());System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));return responseEntity;}} catch (ClientProtocolException e) {e.printStackTrace();} catch (ParseException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {// 释放资源if (httpClient != null) {httpClient.close();}if (response != null) {response.close();}} catch (IOException e) {e.printStackTrace();}}return null;}// 带参数的Get请求public static HttpEntity getWithParams(String url, Map<String, String> paramMap) {// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)CloseableHttpClient httpClient = HttpClientBuilder.create().build();// 参数StringBuffer params = new StringBuffer();try {// 字符数据最好encoding以下;这样一来,某些特殊字符才能传过去(如:某人的名字就是“&”,不encoding的话,传不过去)for (Map.Entry<String, String> paramsEntry : paramMap.entrySet()) {params.append(paramsEntry.getKey() + "=" + URLEncoder.encode(paramsEntry.getValue(), "utf-8"));params.append("&");}params.deleteCharAt(params.length() - 1);} catch (UnsupportedEncodingException e1) {e1.printStackTrace();}// 创建Get请求HttpGet httpGet = new HttpGet(url + "?" + params);// 响应模型CloseableHttpResponse response = null;try {// 配置信息RequestConfig requestConfig = RequestConfig.custom()// 设置连接超时时间(单位毫秒).setConnectTimeout(5000)// 设置请求超时时间(单位毫秒).setConnectionRequestTimeout(5000)// socket读写超时时间(单位毫秒).setSocketTimeout(5000)// 设置是否允许重定向(默认为true).setRedirectsEnabled(true).build();// 将上面的配置信息 运用到这个Get请求里httpGet.setConfig(requestConfig);// 由客户端执行(发送)Get请求response = httpClient.execute(httpGet);// 从响应模型中获取响应实体HttpEntity responseEntity = response.getEntity();System.out.println("响应状态为:" + response.getStatusLine());if (responseEntity != null) {System.out.println("响应内容长度为:" + responseEntity.getContentLength());System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));return responseEntity;}} catch (ClientProtocolException e) {e.printStackTrace();} catch (ParseException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {// 释放资源if (httpClient != null) {httpClient.close();}if (response != null) {response.close();}} catch (IOException e) {e.printStackTrace();}}return null;}// 不带参数的post请求public static HttpEntity postWithoutParam(String url){// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)CloseableHttpClient httpClient = HttpClientBuilder.create().build();// 创建Post请求HttpPost httpPost = new HttpPost(url);// 响应模型CloseableHttpResponse response = null;try {// 由客户端执行(发送)Post请求response = httpClient.execute(httpPost);// 从响应模型中获取响应实体HttpEntity responseEntity = response.getEntity();System.out.println("响应状态为:" + response.getStatusLine());if (responseEntity != null) {System.out.println("响应内容长度为:" + responseEntity.getContentLength());System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));return responseEntity;}} catch (ClientProtocolException e) {e.printStackTrace();} catch (ParseException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {// 释放资源if (httpClient != null) {httpClient.close();}if (response != null) {response.close();}} catch (IOException e) {e.printStackTrace();}}return null;}
// 带参数的Post请求public static String getStrToPostWithParams(String url,JSONObject params) throws URISyntaxException {// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)CloseableHttpClient httpClient = HttpClientBuilder.create().build();// 创建Post请求// 参数URI uri = new URI(url);HttpPost httpPost = new HttpPost(uri);// 将user对象转换为json字符串,并放入entity中StringEntity entity = new StringEntity(JSON.toJSONString(params), "UTF-8");// post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中httpPost.setEntity(entity);httpPost.setHeader("Content-Type", "application/json;charset=utf8");// 响应模型CloseableHttpResponse response = null;try {// 由客户端执行(发送)Post请求response = httpClient.execute(httpPost);// 从响应模型中获取响应实体byte[] bytes = EntityUtils.toByteArray(response.getEntity());System.out.println("响应状态为:" + response.getStatusLine());if (bytes != null) {String resultStr = new String(bytes,"UTF-8");JSONObject jsonObject = JSONObject.parseObject(resultStr);return jsonObject.toJSONString();}} catch (ClientProtocolException e) {e.printStackTrace();} catch (ParseException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {// 释放资源if (httpClient != null) {httpClient.close();}if (response != null) {response.close();}} catch (IOException e) {e.printStackTrace();}}return null;}}
Demo
public class demo {public static void main(String[] args) throws JSONException, URISyntaxException, IOException {String url = "http://localhost:8000/post";JSONObject params = new JSONObject();params.put("eee","eee");
// HttpEntity httpEntity = HttpClientUtils.postWithParams(url, params);String strToPostWithParams = HttpClientUtils.getStrToPostWithParams(url, params);JSONObject jsonObject = JSONObject.parseObject(strToPostWithParams);System.out.println(jsonObject.get("code"));}
}
测试接口
@PostMapping("/post")@ResponseBodypublic JSONObject test(@RequestBody JSONObject data){System.out.println(data);JSONObject result = new JSONObject();result.put("code",1);return result;}
httpClient请求接口,用httpEntity接受结果相关推荐
- HttpClient 如何设置请求接口等待时间
我们在请求接口的时候容易出现请求超时的现象,出现这一问题的原因可能是接口确实挂了,也可能是接口还没有来的及响应,我们程序里面已经出现了请求超时的现象 问题描述: 通常会出现以下的报错: java.ne ...
- httpclient请求webservice接口
1.soapui新建一个webservice地址,例如http://www.webxml.com.cn/WebServices/TranslatorWebService.asmx?wsdl 2. 3. ...
- Java HttpClient 如何使用代理IP请求接口
实际场景中,可能会遇到需要使用代理IP请求接口的需求,所以这里给大家分享一下如何通过代理IP请求接口. proxyServer 代理IP proxyPort 代理端口 HttpClient httpC ...
- java无响应_Java HttpClient请求无响应解决方案
首先来看下多线程处理的流程: 在来看下:httpClient请求工具方法: public static String sendGetRequest(String reqURL, String deco ...
- HttpClient请求范文示例,及注意点提示
1.需求:A项目同步B项目数据表中符合A项目的数据,并添加到A项目自己的表中 2.分析:根据此需求,可以得到的信息很明显 ① 查询符合A条件的B项目表数据 ② 将符合条件的数据,同步添加到A项目表中 ...
- 微信公众号开发 公众号接口开发 封装统一的GET/POST请求接口
10万+IT人都在关注,史上最全面的微信开发实战教程:包含公众号,小程序,微信支付等开发案例 欢迎关注笔者个人博客:http://blogs.chenyunkeji.com/ 在微信公众号/小程序开发 ...
- HttpClient远程接口调用-实名认证
1.HttpClient远程接口调用 1)用户注册 注册按钮button提交表单时,要return false form表单 <!-- action="http://localhost ...
- OpenTSDB之HTTP请求接口、Java开发
OpenTSDB之HTTP请求接口.Java开发 HTTP API 数据写入 查询数据 Timestamp Filtering Aggregation downsample(采样功能) 执行顺序 Ra ...
- httpclient 调取接口_使用HttpClient调用接口的实例讲解
一,编写返回对象 public class HttpResult { // 响应的状态码 private int code; // 响应的响应体 private String body; get/se ...
最新文章
- cvGetSubRect与cvMul用法
- OCR光学字符识别方法汇总(附开源代码)
- 【转】C# 调用 C++ 数据转换
- java 23种设计模式及具体例子 收藏有时间慢慢看
- MyBatis 解决了什么问题?
- 编程语言里函数方法类型检查的重要性
- css animation动画
- Slardar Sql Mapper Framework for Java( Java 持久层框架一枚~)
- 【输入法】Rime-中州韵 基本设置 附:官方定制指南
- 使用gson解决java对象循环引用问题
- was环境通过HTTPS访问其他域名报错 CWPKI0022E: SSL 握手故障:已从目标主机:端口“。。。...
- C/C++指针和取地址操作
- Scrapy豆瓣电影top250(excel保存和图片下载)
- 你的伙伴对你最大会话_TeamViewer许可证对您与伙伴的最大会话有所限制解决办法...
- ppt流程图按步骤链接_【PPT教程】在PowerPoint中5分钟制作一个流程图
- 趣味数学--用1到9这九个数组成一个四位数乘以一位数等于四位数的等式,每个数只能用一次
- Premiere Pro 快捷键大全(2023版)
- bim 模型web页面展示_一种基于BIM模型的Web端轻量化展示方法与流程
- onMeasure实例分析
- 基于STM32的双蓝牙通信