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;
    }

}

 

相关文章

可以认为OpenFeign是Feign的增强版,不同的是OpenFeign支持S...
为进一步规范小程序交易生态、提升用户购物体验、满足用户在...
云原生之使用Docker部署Dashdot服务器仪表盘
本文主要描述TensorFlow之回归模型的基本原理
1.漏洞描述Apache Druid 是一个集时间序列数据库、数据仓库和...
内部类(当作类中的一个普通成员变量,只不过此成员变量是cl...