一个简单的http调用api请求

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

以下是一个简单的示例:

private HttpResponse post(String url, Object body) throws IOException, LklPayApiException {
    String message = JSONObject.toJSONString(body);
    List 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请求更简化,减少了依赖,同时也提高了效率。

你可能感兴趣的:(java,servlet,html)