java发送post请求传json数据
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.apache.http.HttpResponse; 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; //定义发送数据 JSONObject param = new JSONObject(); param.put("username", "zhangshan"); param.put("age", "18"); //定义接收数据 JSONObject result = new JSONObject(); String url = "http://www.baidu.com"; HttpPost httpPost = new HttpPost(url); CloseableHttpClient client = HttpClients.createDefault(); //请求参数转JOSN字符串 StringEntity entity = new StringEntity(param.toString(), "UTF-8"); entity.setContentEncoding("UTF-8"); entity.setContentType("application/json"); httpPost.setEntity(entity); try { HttpResponse response = client.execute(httpPost); if (response.getStatusLine().getStatusCode() == 200) { result = JSON.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8")); } } catch (IOException e) { e.printStackTrace(); result.put("error", "连接错误!"); }
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.78</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency>
测试类(无需maven的方式)
如果是放在测试类,则需要额外再加一个依赖jar包
例如如下的HttpPostTest.java:
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.apache.http.HttpResponse; 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 java.io.IOException; /** * @author qiuqiu_xqy */ public class HttpPostTest { public static void main(String[] args) { //定义发送数据 JSONObject param = new JSONObject(); param.put("username", "zhangshan"); param.put("age", "18"); //定义接收数据 JSONObject result = new JSONObject(); String url = "http://www.baidu.com"; HttpPost httpPost = new HttpPost(url); CloseableHttpClient client = HttpClients.createDefault(); //请求参数转JOSN字符串 StringEntity entity = new StringEntity(param.toString(), "UTF-8"); entity.setContentEncoding("UTF-8"); entity.setContentType("application/json"); httpPost.setEntity(entity); try { HttpResponse response = client.execute(httpPost); if (response.getStatusLine().getStatusCode() == 200) { result = JSON.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8")); } } catch (IOException e) { e.printStackTrace(); result.put("error", "连接错误!"); } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人