Java模拟发送Http请求详细示例

对接第三方接口,肯定是需要我们自己模拟浏览器来发送请求的,有的文档中有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("?");
				else
					url.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;
	}

}

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,您可以使用 Java 中的 HttpURLConnection 类来模拟发送 POST 请求。下面是一个示例代码: ```java import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class PostmanSimulation { public static void main(String[] args) throws Exception { String url = "http://localhost:8080/api/createUser"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // 请求方法设为 POST con.setRequestMethod("POST"); // 添加请求头 con.setRequestProperty("User-Agent", "Mozilla/5.0"); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); // 发送 POST 请求 con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes("username=test&password=123456"); wr.flush(); wr.close(); // 获取响应码和响应结果 int responseCode = con.getResponseCode(); System.out.println("\nSending 'POST' request to URL : " + url); System.out.println("Post parameters : " + "username=test&password=123456"); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // 打印响应结果 System.out.println(response.toString()); } } ``` 在这个示例代码中,我们首先设定了要发送 POST 请求的 URL 地址(这里是 localhost 上的一个测试接口),然后设置了一些请求头属性。紧接着,我们使用 DataOutputStream 将请求参数写入输出流中,并发送给服务器。接下来是获取响应码和响应结果的过程,最后输出了响应结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Eric-x

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值