一个简单的http调用api请求

该示例展示了如何利用Java内置的HttpURLConnection类执行POST请求,设置请求头并处理响应。如果需要SSL加密,可以通过设置SSLSocketFactory实现。此方法减少了对外部库的依赖,简化了HTTP请求的实现。
摘要由CSDN通过智能技术生成

好的,如果你只需要一个简单的http请求,可以使用Java自带的java.net.HttpURLConnection类来处理。

以下是一个简单的示例:

private HttpResponse post(String url, Object body) throws IOException, LklPayApiException {
    String message = JSONObject.toJSONString(body);
    List<String> notPrintList = Arrays.asList(LklConstant.UPLOAD_FILE_API, LklConstant.REPLENISH_FILE_API);
    if (!notPrintList.contains(url)) {
        log.info("send url: {},\n body: {}", url, message);
    }
    String authorization = getAuthorization(message);
    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    connection.setRequestMethod("POST");
    connection.addRequestProperty("Authorization", lklPayConfig.getSchemaName() + " " + authorization);
    connection.addRequestProperty("Accept", "application/json");
    connection.addRequestProperty("Content-Type", "application/json");
    connection.setDoOutput(true);
    try (OutputStream outputStream = connection.getOutputStream()) {
        outputStream.write(message.getBytes(StandardCharsets.UTF_8));
    }
    int responseCode = connection.getResponseCode();
    if (responseCode >= 300) {
        throw new LklPayApiException("HTTP error code: " + responseCode);
    }
    StringBuilder responseText = new StringBuilder();
    try (BufferedReader reader = new BufferedReader(
            new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
        String line;
        while ((line = reader.readLine()) != null) {
            responseText.append(line);
        }
    }
    return new HttpResponse(responseCode, responseText.toString());
}

这里使用了Java自带的HttpURLConnection来发送HTTP请求。和之前不同的是,它不需要使用SSLContext,可以直接进行http请求。

这个示例中,我们没有使用ssl加密,如果你的API需要使用ssl加密,则需要添加下面这行代码设置:
`((HttpsURLConnection) connection).setSSLSocketFactory(sslSocketFactory);`

总之,这样做使Http请求更简化,减少了依赖,同时也提高了效率。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值