java代码模拟postman的raw格式进行HTTP请求

    public static void main(String[] args) throws IOException {

        JSONObject json = new JSONObject();
        json.put("product_id","65346928");
        String token = "12_ooJw2CNx2O2N3JIEt4D1w-Wi86JbHExyHZ5WMo4hETjLp5tZUe9GE6M2Mmi0cL9QXBzrPxPhl-9j34rrHSDy8Q8DYheZ45XKddYjriDd6bsdnzfCKjrLqTv1cazsVJjB0P_LCBGVxr4idB1TSEDeABAHTS";
        String url = "https://api.weixin.qq.com/product/spu/get?access_token="+token;
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        StringEntity postingString = new StringEntity(json.toJSONString(), ContentType.APPLICATION_JSON);// json传递
        post.setEntity(postingString);
        post.setHeader("Content-type", "application/json");
        HttpResponse response = httpClient.execute(post);
        String content = EntityUtils.toString(response.getEntity());
        System.out.println(content);

        JSONObject jsonObject = JSONObject.parseObject(content);
        System.out.println(jsonObject);

    }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
好的,您可以使用 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 将请求参数写入输出流中,并发送给服务器。接下来是获取响应码和响应结果的过程,最后输出了响应结果。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值