对接第三方接口,肯定是需要我们自己模拟浏览器来发送请求的,有的文档中有demo,有demo改一改参数配置就好了,但有的接口却没有demo,只有一份接口参数介绍文档,这时候就需要我们自己来写发送请求的代码了。


使用依赖

<!-- httpclient 相关依赖-->
<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpcore</artifactId><version>4.4.10</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.6</version>
</dependency>
<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpmime</artifactId><version>4.5</version>
</dependency>

请求代码如下:

// 创建Http实例
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建HttpPost实例
HttpPost httpPost = new HttpPost(ocrProperties.getApiUrl());//url post请求url
try {MultipartEntityBuilder builder = MultipartEntityBuilder.create();builder.setCharset(java.nio.charset.Charset.forName("UTF-8"));builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//paramMap 表单里其他参数Map<String, String> paramMap = new HashMap<>();paramMap.put("appId", ocrProperties.getAppId());paramMap.put("appKey", ocrProperties.getAppkey());paramMap.put("image", encode(pictureFile.getBytes()));paramMap.put("fixMode", "1");//‘1’ - 修复模式 ‘0’ - 不修复模式//表单中参数for (Map.Entry<String, String> entry : paramMap.entrySet()) {builder.addPart(entry.getKey(), new StringBody(entry.getValue(), ContentType.create("text/plain", Consts.UTF_8)));}HttpEntity entity = builder.build();httpPost.setEntity(entity);HttpResponse response = httpClient.execute(httpPost);// 执行提交if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {//返回的数据String res = EntityUtils.toString(response.getEntity(), java.nio.charset.Charset.forName("UTF-8"));//解析JSON,将JSON转换为JsonObject对象JsonObject asJsonObject = jsonParser.parse(res).getAsJsonObject();if(null != asJsonObject){//响应code码。200000:成功,其他失败String code = asJsonObject.get("code").getAsString();if("200000".equals(code)){//获取json元素,这里的格式比较复杂,需要多次转换,属于是json套json了JsonObject element = asJsonObject.get("data").getAsJsonObject().get("data").getAsJsonObject().getAsJsonObject("words_result").getAsJsonObject();//获取指定元素String companyName = element.getAsJsonObject("单位名称").get("words").getAsString();//公司名称String creditCode = element.getAsJsonObject("社会信用代码").get("words").getAsString();//社会信用代码String legalPerson = element.getAsJsonObject("法人").get("words").getAsString();//法人/公司代表人String address = element.getAsJsonObject("地址").get("words").getAsString();//地址map.put("companyName",companyName);map.put("creditCode",creditCode);map.put("legalPerson",legalPerson);map.put("address",address);}}}
} catch (Exception e) {e.printStackTrace();log.error("调用HttpPost失败!" + e.toString());
} finally {if (httpClient != null) {try {httpClient.close();} catch (IOException e) {log.error("关闭HttpPost连接失败");}}
}

使用的话把上面的代码改一改就好了,一般都是把这种封装为工具类使用的。


方式二

//1.根据订单号查询订单信息QueryWrapper<Order> wrapper = new QueryWrapper<>();wrapper.eq("order_no",orderNo);Order order = orderService.getOne(wrapper);//2.使用map设置生成二维码需要的参数Map m = new HashMap<>();//设置支付参数m.put("appid", "wx74862e0dfcf69954");m.put("mch_id", "1558950191");m.put("nonce_str", WXPayUtil.generateNonceStr());m.put("body", order.getCourseTitle());m.put("out_trade_no", orderNo);m.put("total_fee", order.getTotalFee().multiply(new BigDecimal("100")).longValue() + "");m.put("spbill_create_ip", "127.0.0.1");m.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify\n");m.put("trade_type", "NATIVE");//3.发送httpclient请求,传递参数HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");//将map数据集合转换为xml格式client.setXmlParam(WXPayUtil.generateSignedXml(m, "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));client.setHttps(true);//设置支持https请求//执行请求发送client.post();//4.得到发送请求返回结果//返回的内容是xml格式String xml = client.getContent();Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);//封装返回结果集Map map = new HashMap<>();map.put("out_trade_no", orderNo);               //订单号map.put("course_id", order.getCourseId());      //课程id(支付成功返回页面需要用到)map.put("total_fee", order.getTotalFee());      //价格map.put("result_code", resultMap.get("result_code"));//返回二维码状态码map.put("code_url", resultMap.get("code_url"));//二维码地址

用到的工具类

package com.atguigu.eduorder.utils;import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.ParseException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;/*** http请求客户端** @author Eric**/
public class HttpClient {private String url;private Map<String, String> param;private int statusCode;private String content;private String xmlParam;private boolean isHttps;public boolean isHttps() {return isHttps;}public void setHttps(boolean isHttps) {this.isHttps = isHttps;}public String getXmlParam() {return xmlParam;}public void setXmlParam(String xmlParam) {this.xmlParam = xmlParam;}public HttpClient(String url, Map<String, String> param) {this.url = url;this.param = param;}public HttpClient(String url) {this.url = url;}public void setParameter(Map<String, String> map) {param = map;}public void addParameter(String key, String value) {if (param == null)param = new HashMap<String, String>();param.put(key, value);}public void post() throws ClientProtocolException, IOException {HttpPost http = new HttpPost(url);setEntity(http);execute(http);}public void put() throws ClientProtocolException, IOException {HttpPut http = new HttpPut(url);setEntity(http);execute(http);}public void get() throws ClientProtocolException, IOException {if (param != null) {StringBuilder url = new StringBuilder(this.url);boolean isFirst = true;for (String key : param.keySet()) {if (isFirst)url.append("?");elseurl.append("&");url.append(key).append("=").append(param.get(key));}this.url = url.toString();}HttpGet http = new HttpGet(url);execute(http);}/*** set http post,put param*/private void setEntity(HttpEntityEnclosingRequestBase http) {if (param != null) {List<NameValuePair> nvps = new LinkedList<NameValuePair>();for (String key : param.keySet())nvps.add(new BasicNameValuePair(key, param.get(key))); // 参数http.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); // 设置参数}if (xmlParam != null) {http.setEntity(new StringEntity(xmlParam, Consts.UTF_8));}}private void execute(HttpUriRequest http) throws ClientProtocolException,IOException {CloseableHttpClient httpClient = null;try {if (isHttps) {SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {// 信任所有public boolean isTrusted(X509Certificate[] chain,String authType)throws CertificateException {return true;}}).build();SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();} else {httpClient = HttpClients.createDefault();}CloseableHttpResponse response = httpClient.execute(http);try {if (response != null) {if (response.getStatusLine() != null)statusCode = response.getStatusLine().getStatusCode();HttpEntity entity = response.getEntity();// 响应内容content = EntityUtils.toString(entity, Consts.UTF_8);}} finally {response.close();}} catch (Exception e) {e.printStackTrace();} finally {httpClient.close();}}public int getStatusCode() {return statusCode;}public String getContent() throws ParseException, IOException {return content;}}

Java模拟发送Http请求详细示例相关推荐

  1. Java模拟发送post请求

    项目要求:模拟100个温湿度设备发送温湿度数据进行压测,查看数据是否有叠加且显示正确,因为测试环境简陋,没有100个温湿度设备,只能通过调用接口模拟发送请求,由于每次发送的请求要求正文某些元素值要唯一 ...

  2. java httpclient发送json 请求 ,go服务端接收

    /***java客户端发送http请求*/package com.xx.httptest;/*** Created by yq on 16/6/27.*/import java.io.IOExcept ...

  3. jmeter测试TCP服务器/模拟发送TCP请求

    jmeter测试TCP服务器,使用TCP采样器模拟发送TCP请求. TCP采样器:打开一个到指定服务器的TCP / IP连接,然后发送指定文本并等待响应. jmeter模拟发送TCP请求的方法: 1. ...

  4. 使用谷歌浏览器模拟发送http请求

    下载一个chromed的插件postman附上下载地址http://download.csdn.net/detail/zhenghui89/8490331;下载以后解压缩;打开谷歌浏览器以后   依次 ...

  5. curl/wget 模拟发送post请求

    curl/wget 模拟发送post请求 curl -H "这里是请求header信息" -X POST -d "这里是请求body体"  ip:port -O ...

  6. JAVA后台发送http请求

    JAVA后台发送http请求 代码: @RequestMapping("/check")@ResponseBodypublic Map check(Integer cashReco ...

  7. Java 常用工具类(12) : java后台发送http请求

    参考 : java http 发送post请求-json格式_Oh_go_boy的博客-CSDN博客 Java发送Http请求 - 玄同太子 - 博客园 org.apache.http 在Maven中 ...

  8. java后台发送https请求(基于httpTemplate的httpUtil工具实现)

    最近做连续做了一些java后台发送http请求的需求,发现项目里实现http请求的写法各异,不够简洁统一,于是基于httpTemplate自行封装了一个http请求工具,常见的json和octet-s ...

  9. java实现请求发送_java实现响应重定向发送post请求操作示例

    本文实例讲述了java实现响应重定向发送post请求操作.分享给大家供大家参考,具体如下: 关于重定向我们用的比较多的还是redirect:重定向,默认发送的get请求. return "r ...

最新文章

  1. 2021年大数据Flink(四十五):​​​​​​扩展阅读 双流Join
  2. 百度飞桨成为北京市首个AI产业方向创新应用平台
  3. 要学习机器学习,先从这十大算法开始吧
  4. 2017年智能家居将从概念走进现实
  5. Warning: Mapping new ns http://schemas.android.com/repository/android/common/02 to old ns http://sch
  6. win10 安装 tensorflow gpu 版
  7. 关于SAP Spartacus Routing 页面上下文切换机制的实现
  8. Python基础—08-函数使用(02)
  9. hdu 4006 The kth great number (优先队列)
  10. 【干货】2020十大消费新机遇.pdf(附下载链接)
  11. 不到 1000 元,你的所有隐私竟然都能随便查!!!
  12. 在Linux中查找用户帐户信息和登录详细信息的11种方法
  13. .net体系结构——C#高级编程第一章
  14. python音乐播放器代码_Python简易音乐播放器
  15. 智能电话销售机器人源码搭建部署系统电话机器人源码
  16. 为什么在使用超级终端配置交换机时显示乱码或无显示?
  17. Unity语音合成-初识有道语音合成
  18. delphi 企业微信消息机器人_GitHub - guoxianlong/insight: Insight是一个可以管理企业微信群机器人的小工具,可以非常方便的往群里发布即时消息和定时消息。...
  19. Vue超全资源,收藏!
  20. java 虚拟机内存类_java 虚拟机类加载 及内存结构

热门文章

  1. ガリレオの苦悩 密室る 1
  2. python中返回上一步操作的代码_python基础-文件操作
  3. upload video
  4. 手机获取百度地图定位
  5. 一份品牌加入元宇宙的保姆级指南
  6. 赚钱:在互联网时代,我想带你发家致富
  7. matlab中的Neural Network  Training(nntraintool)界面的解释
  8. 鸿蒙系统4月份升级,华为旗舰手机将在4月起升级鸿蒙系统
  9. CSS3新增属性——新增选择器(属性选择器、结构伪类选择器、伪元素选择器)
  10. 【技术君啃书之旅】web安全之机器学习入门 第三章笔记