HttpUtil.createPost发送post请求
时间: 2023-09-06 11:08:16 浏览: 145
https发送post请求
5星 · 资源好评率100%
HttpUtil.createPost是一个Java类库中的方法,用于创建一个HTTP POST请求对象。该方法通过使用Java的HttpURLConnection类来构建请求对象,并设置请求的URL、请求方法、请求头信息和请求体数据。可以使用以下代码示例来发送一个POST请求:
```
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
public class HttpUtil {
public static void main(String[] args) throws Exception {
String url = "https://example.com/api";
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
String requestBody = "{\"name\":\"John\", \"age\":30}";
String response = sendPostRequest(url, headers, requestBody);
System.out.println(response);
}
public static String sendPostRequest(String url, Map<String, String> headers, String requestBody) throws Exception {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
for (Map.Entry<String, String> entry : headers.entrySet()) {
con.setRequestProperty(entry.getKey(), entry.getValue());
}
con.setDoOutput(true);
con.getOutputStream().write(requestBody.getBytes("UTF-8"));
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
}
```
这个示例发送一个带有请求头和请求体的POST请求,并返回响应的内容。在实际使用中,需要替换URL、请求头和请求体,以及根据实际需求处理响应。
阅读全文