Java HttpClient 改变内容类型(Content-Type)的方法是通过设置请求头(request header)中的 "Content-Type" 属性。以下是一个使用 Java HttpClient 发送 POST 请求并更改内容类型的示例:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class Main {
public static void main(String[] args) throws IOException {
String url = "https://example.com/api";
String json = "{\"key\": \"value\"}";
URL obj = new URL(url);
HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
connection.setRequestProperty("Accept", "application/json");
connection.setDoOutput(true);
connection.getOutputStream().write(json.getBytes(StandardCharsets.UTF_8));
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
} else {
System.out.println("Request failed. Response code: " + responseCode);
}
}
}
在这个示例中,我们使用 HttpURLConnection 发送一个 POST 请求,并设置请求头中的 "Content-Type" 为 "application/json;charset=UTF-8"。这将告诉服务器我们发送的数据是 JSON 格式的。同时,我们还设置了 "Accept" 请求头,表示我们期望服务器返回的数据类型是 JSON。
领取专属 10元无门槛券
手把手带您无忧上云