java通用post请求

2022/7/17 1:17:45

本文主要是介绍java通用post请求,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

package com.example.climbnumber.yzm;

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;
public class Test04 {

    public static void main(String[] args) {
        JSONObject jsonObject = JSONObject.parseObject("{\n" +
                "  \"body\": {\n" +
                "    \"uuid\": \"\",\n" +
                "    \"scenes\": \"xxxx(91522301MA6DJJYG2C)\"\n" +
                "  },\n" +
                "  \"head\": {\n" +
                "    \"transCode\": \"\",\n" +
                "    \"traceId\": \"\"\n" +
                "  }\n" +
                "}");
        JSONObject result = sendPost("www.baidu.com",jsonObject);
        System.out.println("================================");
        System.out.println(result.toJSONString());
    }


    public static JSONObject sendPost(String url,JSONObject param){
        //定义接收数据
        JSONObject result = new JSONObject();
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpClient client = HttpClients.createDefault();
        //请求参数转JOSN字符串
        StringEntity entity = new StringEntity(param.toJSONString(), "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 (Exception e) {
            e.printStackTrace();
            result.put("error", "连接错误!");
        }
        return result;
    }

}

 



这篇关于java通用post请求的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程