http协议调用第三方接口(post get方法)

本文介绍了一个使用Java实现的HTTP客户端工具类,包括GET和POST请求的方法。该工具类使用了PoolingHttpClientConnectionManager来管理连接池,提高了并发请求的效率,并设置了超时时间和响应头,以适应JSON格式的数据交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class PostUtil {
    private static CloseableHttpClient httpClient;

    static {
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(100);
        cm.setDefaultMaxPerRoute(20);
        cm.setDefaultMaxPerRoute(50);
        httpClient = HttpClients.custom().setConnectionManager(cm).build();
    }

    public static String get(String url) {
        CloseableHttpResponse response = null;
        BufferedReader in = null;
        String result = "";
        try {
            HttpGet httpGet = new HttpGet(url);
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setConnectionRequestTimeout(30000).setSocketTimeout(30000).build();
            httpGet.setConfig(requestConfig);
            httpGet.setConfig(requestConfig);
            httpGet.addHeader("Content-type", "application/json; charset=utf-8");
            httpGet.setHeader("Accept", "application/json");
            response = httpClient.execute(httpGet);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();
            result = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static String post(String url, String jsonString) {
        CloseableHttpResponse response = null;
        BufferedReader in = null;
        String result = "";
        try {
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setConnectionRequestTimeout(30000).setSocketTimeout(30000).build();
            httpPost.setConfig(requestConfig);
            httpPost.setConfig(requestConfig);
            httpPost.addHeader("Content-type", "application/json; charset=utf-8");
            httpPost.setHeader("Accept", "application/json");
            httpPost.setEntity(new StringEntity(jsonString, Charset.forName("UTF-8")));
            response = httpClient.execute(httpPost);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();
            result = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

}

### Java 中通过 GETPOST 方法调用第三方 API #### 使用 `HttpURLConnection` 类发送 HTTP 请求 在 Java 中可以利用原生的 `java.net.HttpURLConnection` 来发起网络请求。对于 GETPOST 请求来说,主要区别在于设置连接属性以及处理数据的方式。 针对 GET 请求: ```java URL url = new URL("http://example.com/api?param=value"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); // 设置请求方式为GET // 添加必要的HTTP头部信息 conn.setRequestProperty("Accept", "application/json"); int responseCode = conn.getResponseCode(); // 获取响应码 if(responseCode == HttpURLConnection.HTTP_OK){ BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; StringBuilder content = new StringBuilder(); while ((inputLine = in.readLine()) != null) { content.append(inputLine); } in.close(); System.out.println(content.toString()); // 输出返回的内容 } else{ System.out.println("GET request failed."); } ``` 上述代码展示了如何构建一个简单的 GET 请求并读取服务器端传回的数据[^1]。 而对于 POST 请求,则需额外准备要提交的数据体,并将其写入到输出流中去: ```java String param = "key1=value1&key2=value2"; // 参数字符串形式 URL url = new URL("http://example.com/postApiEndpoint"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); // 启用输出模式 conn.setRequestMethod("POST"); // 设置请求方式为POST conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); OutputStream os = conn.getOutputStream(); os.write(param.getBytes()); os.flush(); os.close(); BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8)); StringBuilder response = new StringBuilder(); String responseLine; while((responseLine = br.readLine())!=null){ response.append(responseLine.trim()); } System.out.println(response.toString()); br.close(); ``` 这段程序说明了怎样构造带有表单参数的 POST 请求,并接收来自服务端的信息作为回应[^2]。 为了简化开发过程中的重复劳动,通常会创建专门用于封装这些操作的帮助函数或是工具类来统一管理不同类型的 HTTP 请求逻辑[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值