欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java发送http请求发送json对象

程序员文章站 2022-04-03 08:38:36
...
 http工具类:

public static String httpPostWithjson(String url, String json) throws IOException {
    String result = "";
    HttpPost httpPost = new HttpPost(url);
    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {
        BasicResponseHandler handler = new BasicResponseHandler();
        StringEntity entity = new StringEntity(json, "utf-8");//解决中文乱码问题
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        result = httpClient.execute(httpPost, handler);
        return result;
    } catch (Exception e) {
        e.printStackTrace();

    } finally {
        try {
            httpClient.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return result;
}
测试:
String httpURL = "http://localhost:8080/xxxxxx/orgnameRentArea/save.do";
try {
    OrgnameRentArea rentArea = new OrgnameRentArea();
    rentArea.setProjectId("1");
    rentArea.setRegularrentName("1");
    BigDecimal bigDecimal = new BigDecimal(2);
    rentArea.setRegularuseArea(bigDecimal);
    rentArea.setTempraturEarea(1);
    rentArea.setIsflag(1);
    rentArea.setStartTime("1");
    JSONObject jsonObject = JSONObject.fromObject(rentArea);
    String result1 = httpPostWithjson(httpURL, jsonObject.toString());
} catch (IOException e) {
    e.printStackTrace();
}

 

相关标签: 开发经验