java http 401,如何获取响应正文使用java.net.HttpURLConnection,当返回401?

this is my first question on stack, I hope I'll find some help :)

I have problem with retrieving Json response in case when server returns error. See details below.

How do I perform request

I use following libraries:

import java.net.HttpURLConnection;

import java.net.MalformedURLException;

import java.net.URL;

First, I setup request properties:

conn.setRequestProperty("Accept", "application/json");

url = new URL(www.example.com);

conn = (HttpURLConnection) url.openConnection();

conn.setRequestMethod(requestType);

conn.setRequestProperty("Authorization", token);

After that, when request is successful, I get response Json:

br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

sb = new StringBuilder();

String output;

while ((output = br.readLine()) != null) {

sb.append(output);

return sb.toString();

... and the problem is:

I can't retrieve Json received when the server returns some error like 50x or 40x,. Following line throws IOException:

br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

// result: java.io.IOException: Server returned HTTP response code: 401 for URL: www.example.com

The server sends body for sure, I see it in external tool Burp Suite:

HTTP/1.1 401 Unauthorized

{"type":"AuthApiException","message":"AuthApiException","errors":[{"field":"email","message":"Invalid username and/or password."}]}

I can get response message (i.e. "Internal Server Error") and code (i.e. "500") using following methods:

conn.getResponseMessage();

conn.getResponseCode();

So I can't retrieve Json response... maybe there is some method I didn't notice in the library? Please help...

I know there are ways around like changing the library (How can I get an http response body as a string in Java?), but I don't want to change The library.

解决方案

If the response code isn't 200 or 2xx, use getErrorStream() instead of getInputStream().

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值