我与一个HttpsURLConnection的一个问题,即我似乎无法解决。基本上,我送了一些信息到服务器,如果一些数据是错误的,服务器发送了我一个500响应代码。然而,它也将在响应告诉我哪个位数据的消息是错误的。问题是,消息总是空的,当我在看过。我想这是因为可以读取流之前filenotfound例外总是被抛出。我对吗?我试着读errorstream以及但这始终是空的。这里的一个片段:

    conn = (HttpsURLConnection) connectURL.openConnection();
    conn.setDoOutput(true);
    conn.setConnectTimeout(30000);
    conn.setReadTimeout(30000);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Length",
         Integer.toString(outString.getBytes().length));
    DataOutputStream wr = new DataOutputStream(conn
      .getOutputStream());
    wr.write(outString.getBytes());
    wr.flush();
    wr.close();
    if(conn.getResponseCode>400{

    String response = getErrorResponse(conn);

    public String getErrorResponse(HttpsURLConnection conn) {
    Log.i(TAG, "in getResponse");
    InputStream is = null;
    try {

     //is = conn.getInputStream();
    is = conn.getErrorStream();
    // scoop up the reply from the server
    int ch;
    StringBuffer sb = new StringBuffer();
    while ((ch = is.read()) != -1) {
     sb.append((char) ch);
    }
    //System.out.println(sb.toString());
    return sb.toString();
    // return conferenceId;
   }
    catch (Exception e){
    e.printStackTrace();
    }
    }
有帮助吗?

解决方案

所以才跟进这一点,这里是我如何解决它:

public static String getResponse(HttpsURLConnection conn) {
    Log.i(TAG, "in getResponse");
    InputStream is = null;
    try {
        if(conn.getResponseCode()>=400){
            is = conn.getErrorStream();
        }
        else{
            is=conn.getInputStream();
        }
        ...read stream...
}

似乎调用它们像这样产生与消息的错误流。感谢您的建议!

scroll top