当Java应用程序在处理HTTP请求时遇到401未授权错误,通常意味着客户端未能提供有效的身份验证凭据,或者提供的凭据不被服务器接受。为了捕获POST请求的JSON响应,你可以使用Java中的HTTP客户端库,如HttpURLConnection
或第三方库,如Apache HttpClient或OkHttp。
以下是使用HttpURLConnection
捕获POST请求的JSON响应的步骤:
URL url = new URL("http://example.com/api/resource");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Authorization", "Bearer YOUR_ACCESS_TOKEN");
connection.setDoOutput(true);
try (OutputStream os = connection.getOutputStream()) {
byte[] input = "{\"key\":\"value\"}".getBytes("utf-8");
os.write(input, 0, input.length);
}
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
// 捕获401错误
try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getErrorStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
// 这里处理JSON响应
System.out.println(response.toString());
}
}
如果响应码不是401,你可以继续处理正常的响应流:
if (responseCode == HttpURLConnection.HTTP_OK) {
try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
// 这里处理JSON响应
System.out.println(response.toString());
}
}
connection.disconnect();
YOUR_ACCESS_TOKEN
)是有效的,并且具有访问所需资源的权限。如果你更喜欢使用第三方库,比如Apache HttpClient,代码会更加简洁:
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost request = new HttpPost("http://example.com/api/resource");
request.setHeader("Content-Type", "application/json");
request.setHeader("Authorization", "Bearer YOUR_ACCESS_TOKEN");
StringEntity params = new StringEntity("{\"key\":\"value\"}", "UTF-8");
request.setEntity(params);
try (CloseableHttpResponse response = httpClient.execute(request)) {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
HttpEntity entity = response.getEntity();
if (entity != null) {
String result = EntityUtils.toString(entity);
// 处理JSON响应
System.out.println(result);
}
}
} catch (IOException e) {
e.printStackTrace();
}
在这个例子中,我们使用了Apache HttpClient库来发送POST请求,并捕获了401未授权错误的响应。这种方法提供了更多的灵活性和功能,但需要添加相应的依赖到你的项目中。
确保你的项目中包含了必要的依赖,例如,如果你使用Apache HttpClient,你需要在项目的构建文件中添加以下依赖:
对于Maven:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
对于Gradle:
implementation 'org.apache.httpcomponents:httpclient:4.5.13'
这样,你就可以捕获并处理Java中的401未授权错误,并获取POST请求的JSON响应了。
领取专属 10元无门槛券
手把手带您无忧上云