我正在创建一个Android应用程序,它将使用xauth身份验证连接到Web服务器。我的问题是,如果服务器返回401导致java异常,我就无法得到响应。
我需要回复才能知道我做错了什么。
首先,HttpURLConnection对这类东西有好处 其次,我怎么能得到回应?
URL u_rl = new URL(url);
final HttpURLConnection connection =
(HttpURLConnection) u_rl.openConnection();
connection.setRequestMethod(method);
if (authorization != null) {
connection.setRequestProperty("Authorization", authorization);
}
final byte[] body = parameters.getBytes();
connection.setRequestProperty(
"Content-Length", Integer.toString(body.length));
connection.setDoOutput(true);
connection.connect();
final OutputStream output = connection.getOutputStream();
output.write(body);
output.flush();
System.out.println(connection.getResponseCode());
if (connection.getResponseCode() != 200) {
result.put("error", connection.getResponseCode()+"");
return null;
}
String out = IOUtils.toString(connection.getInputStream());
我知道为什么我得到400或其他响应代码,问题是用户不知道为什么。服务器在JSON中返回一个错误,即使响应代码不是200,我也想得到那个JSON代码
答案 0 :(得分:2)
除非你提供它,否则很难说出代码中的错误我宁愿建议你使用这个肯定会对你有帮助的答案。
InputStream retrieveStream(String url) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(url);
try {
HttpResponse getResponse = client.execute(getRequest);
final int statusCode = getResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w(getClass().getSimpleName(), "Error " + statusCode
+ " for URL " + url);
return null;
}
HttpEntity getResponseEntity = getResponse.getEntity();
return getResponseEntity.getContent();
} catch (IOException e) {
getRequest.abort();
Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
}
return null;
}
并使用此代码将inputstream转换为String可读数据格式。
BufferedReader r = new BufferedReader(new InputStreamReader(retrieveStream("YOU URL")));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
谢谢:)