2016-04-29 108 views
0

我正在尝试将用户注册到我的Web服务器。如果我向服务器发送有效的详细信息,那么我会收到代表“已创建”的201代码。但是,当我发送错误的凭据到服务器,即相同的用户名,那么我得到400 FileNotFoundException。我需要解释错误细节不仅400个代码。因为如果我使用curl从命令行发送错误的细节,那么我也会得到错误的细节,例如这个用户名已经存在。 这里是我的代码来读取服务器的响应。其实我试过两种不同的方法,但它们都以400(坏请求)相同的错误结束。如何从REST API读取错误详细信息

public static String readResponse(HttpURLConnection connection) 
     throws IOException, JSONException { 

    InputStream is = connection.getInputStream(); 
    BufferedReader rd = new BufferedReader(new InputStreamReader(is)); 
    String line; 
    StringBuilder response = new StringBuilder(); 
    while((line = rd.readLine()) != null) { 
     response.append(line); 
     response.append('\r'); 
    } 
    return response.toString(); 
} 

public static String readResponseFromServer(HttpURLConnection connection) throws IOException { 
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader 
      (connection.getInputStream())); 
    String line = ""; 
    StringBuilder stringBuilder = new StringBuilder(); 
    while ((line = bufferedReader.readLine()) != null) { 
     stringBuilder.append(line).append("\n"); 
    } 
    return stringBuilder.toString(); 
} 

在上面的代码中,有两种读取服务器响应的方法。

这里是我正在如何使用这些方法来从服务器读取

System.out.println("Server Response" + WebServiceHelpers.readResponseFromServer(urlConnection)); 

响应,我也使用第二方法,该方法是readResponse()从上面的代码。

这里是curl命令的截图,其中我向服务器发送错误的细节并获取错误的详细信息。

Server Response using curl

我也有HTTPIE尝试这样做,我也得到尽可能使用curl命令即用户与该用户名已经存在同样的反应。

我在我的Java代码中也需要这些错误细节。我搜索了互联网,但没有找到解决方案。 有什么建议吗?

回答

0

试试这个

public static String readResponse(HttpURLConnection connection) 
    throws IOException, JSONException { 
    int respCode = connection.getResponseCode(); 

    InputStream is = null; 
    if (isErrorCode(respCode)) { 
     is = connection.getErrorStream(); 
    } else if (connection.getErrorStream() != null) { 
     is = connection.getInputStream(); 
    } 
    //FIXME: InputStreamReader must be constructed with right charset 
    BufferedReader rd = new BufferedReader(new InputStreamReader(is)); 
    String line; 
    StringBuilder response = new StringBuilder(); 
    while((line = rd.readLine()) != null) { 
     response.append(line); 
    } 
    return response.toString(); 
} 

写isErrorCode方法。它应该根据需要将响应代码400解释为错误和其他代码。还请注意fixme评论。在构建没有字符集的InputStreamReader时,它使用默认字符集(如果不提供file.encoding属性,则使用UTF-8),但正确的方法是使用该编码从Content-Type响应标头和流程响应主体获取字符集。从响应中提取字符集的方法可能看起来像这样

private String getCharset(HttpURLConnection con) { 
    String charset = ""; 

    String contentType = con.getContentType(); 
    if (contentType != null) { 
     String[] values = contentType.split(";"); 
     for (String value : values) { 
      String trimValue = value.trim(); 

      if (trimValue.toLowerCase().startsWith("charset=")) { 
       charset = trimValue.substring("charset=".length()); 
      } 
     } 
    } 
    if ("".equals(charset)) { 
     charset = "UTF-8"; 
    } 

    return charset; 
}