超级简单的 Java & HttpClient 教程!

羊时铭
2023-12-01

依赖

	    <!-- https://www.runoob.com/w3cnote/fastjson-intro.html -->
	     <dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
		</dependency>
		
		<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.6</version>
        </dependency>

Java代码:对象参数的POST请求

/**
 * 
 */
package com.elink.wdt.roma.util;
import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
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.HttpClients;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;
import com.elink.wdt.roma.param.bodyParam;


public class HttpTool {

	public static String post(String url, String methodType, Integer methodValue) throws ClientProtocolException, IOException {
		// 准备请求
		HttpPost post = new HttpPost(url);

		// 准备参数————————大部分参数放到requestBody中
		JSONObject param = new JSONObject();
		
		bodyParam qe = new bodyParam();
		// 判断工作模式
		if("CommandIn".equals(methodType)) {			//入闸
			qe.setCommandIn(methodValue);
		} else if("CommandOut".equals(methodType)) {	//出闸
			qe.setCommandOut(methodValue);
		} else if ("WorkModeSet".equals(methodType)) {	//工作模式:正常/常开
			qe.setWorkModeSet(methodValue);
		}
		param.put("body", qe);
		
		param.put("deviceType","d1fb52d3-c524-477c-927b-d25fc6b5b339");
		param.put("manufacturerId","12004872-e5c3-4f59-8c15-62dfe0086688");
		param.put("model","e0142a13-5476-411c-960b-3d4473993eba");
		param.put("method",methodType);
		
		// 转换参数类型为StringEntity
		StringEntity requestEntity = new StringEntity(JSONObject.toJSONString(param));
		post.setEntity(requestEntity);

		// 添加请求头
		post.setHeader("Content-Type","application/json");
		post.setHeader("channel","openlab");
		post.setHeader("X-HW-ID","test1");
		post.setHeader("X-HW-APPKEY","4p+I0ybPWSazOhod6g7txA==");
		post.setHeader("deviceCode","5aa05123-cdf0-4e46-b0e8-b2c1b1de96b2");
		post.setHeader("method",methodType);
		
		// 创建发包客户端
		CloseableHttpClient http = HttpClients.createDefault();
		// 通过客户端发包,得到响应
		CloseableHttpResponse responce = http.execute(post);
		// 获得响应中的信息
		HttpEntity entity = responce.getEntity();
		String entityString = EntityUtils.toString(entity);
		return entityString;
	}
}

注意

header、param要注意不要写错,我遇到过“在postman测试时可以,在代码中报错”的问题,比较低级的错误…

 类似资料: