在Java中,如果你遇到415 Unsupported Media Type
错误,通常是因为你发送的请求的Content-Type不正确。以下是使用Java发送HTTP请求的常见方式,以及如何正确设置Content-Type以避免该错误。
使用HttpURLConnection
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpPostExample {
public static void main(String[] args) {
try {
URL url = new URL("http://example.com/api");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json"); // 设置正确的Content-Type
String jsonInputString = "{\"key1\":\"value1\", \"key2\":\"value2\"}";
try (OutputStream os = conn.getOutputStream()) {
byte[] input = jsonInputString.getBytes("utf-8");
os.write(input, 0, input.length);
}
int code = conn.getResponseCode();
System.out.println(code);
} catch (Exception e) {
e.printStackTrace();
}
}
}
使用HttpClient (Apache HttpComponents)
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.http.HttpResponse;
public class HttpClientExample {
public static void main(String[] args) {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost request = new HttpPost("http://example.com/api");
request.setHeader("Content-Type", "application/json"); // 设置正确的Content-Type
String json = "{\"key1\":\"value1\", \"key2\":\"value2\"}";
StringEntity entity = new StringEntity(json);
request.setEntity(entity);
HttpResponse response = httpClient.execute(request);
String result = EntityUtils.toString(response.getEntity());
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
使用HttpClient (Java 11及以上版本)
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpRequest.BodyPublishers;
public class Java11HttpClientExample {
public static void main(String[] args) {
try {
HttpClient client = HttpClient.newHttpClient();
String json = "{\"key1\":\"value1\", \"key2\":\"value2\"}";
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("http://example.com/api"))
.header("Content-Type", "application/json") // 设置正确的Content-Type
.POST(BodyPublishers.ofString(json))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode());
System.out.println(response.body());
} catch (Exception e) {
e.printStackTrace();
}
}
}
检查服务器端
确保服务器端期望接收到的Content-Type确实是你所设置的类型。如果服务器端要求特定的Content-Type,客户端必须匹配这一类型。
其他建议
- 调试工具:使用Postman或cURL工具手动发送请求,确保服务器端工作正常且返回预期响应。
- 日志记录:在服务器端开启详细的日志记录,查看收到的请求头信息,帮助诊断问题。
通过以上方法,你应该能够解决415 Unsupported Media Type
错误。如果问题依然存在,请提供更多上下文或服务器端期望的具体Content-Type信息。