当前位置: 首页 > 工具软件 > http-request > 使用案例 >

httpRequest请求方法

姚宪
2023-12-01

业务场景:

        公司的多个项目之间要进行RestHub接口的调用,采用HTTP的方式,参数用的是JSON,方法如下:

public static StringBuffer post(String url, JSONObject json) {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost(url);
    BufferedReader reader = null;
    StringBuffer sb = new StringBuffer("");
    StringEntity s = new StringEntity(json.toString(), "UTF-8");
    s.setContentEncoding("UTF-8");
    s.setContentType("application/json");
    post.setEntity(s);
    HttpResponse res = null;
    HttpEntity entity = null;
    InputStreamReader isr = null;
    try {
        res = client.execute(post);
        if (res.getStatusLine().getStatusCode() == 200) {
            entity = res.getEntity();
            isr =  new InputStreamReader(entity.getContent(), "utf-8");
            reader = new BufferedReader(isr);
            String lines;
            while ((lines = reader.readLine()) != null) {
                sb.append(lines);
            }
            return sb;
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (isr != null) {
                isr.close();
            }
            if (reader != null) {
                reader.close();
            }
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb;
}

说点儿题外话,需要注意的地方:

1、代码的异常catch的地方不要用e.printStackTrace();而要采用Logger日志的输出方式

2、finally要记得关资源,资源的关闭顺序要与打开顺序相反,关闭之前要有非空判断(判断很重要,sonar会扫描出此处代码有严重问题,find bugs工具也会扫除此处代码有问题)

 类似资料: