欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 艺术 > 通过java.netHttpURLConnection类实现java发送http请求

通过java.netHttpURLConnection类实现java发送http请求

2024/11/30 8:35:44 来源:https://blog.csdn.net/weixin_46018178/article/details/140959537  浏览:    关键词:通过java.netHttpURLConnection类实现java发送http请求

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public static String postForBody(String param) {
try {
URL url = new URL(“https://usapp-open.ulifecam.com”);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // 设置请求方法为POSTconnection.setRequestMethod("POST");// 设置请求头,指示内容类型为JSONconnection.setRequestProperty("Content-Type", "application/json");// 设置请求体byte[] outputInBytes = param.getBytes("UTF-8");int outputLength = outputInBytes.length;// 设置内容长度connection.setRequestProperty("Content-Length", String.valueOf(outputLength));// 默认情况下,该URLConnection的DoOutput属性为false。// 我们需要设置DoOutput为true,表明我们要输出数据。connection.setDoOutput(true);// 发送请求体try (OutputStream os = connection.getOutputStream()) {os.write(outputInBytes, 0, outputLength);}// 获取响应码int responseCode = connection.getResponseCode();// 根据需要获取响应内容if (responseCode == HttpURLConnection.HTTP_OK) { // 200try (java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(connection.getInputStream()))) {String inputLine;StringBuilder response = new StringBuilder();while ((inputLine = in.readLine()) != null) {response.append(inputLine);}System.out.println("Response Body: " + response.toString());return response.toString();}}// 关闭连接connection.disconnect();return null;} catch (Exception e) {e.printStackTrace();}return null;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com