5

我似乎无法解决 HttpsURLConnection 的问题。基本上,我正在向服务器发送一些信息,如果其中一些数据有误,服务器会向我发送一个 500 响应代码。但是,它还会在响应中发送一条消息,告诉我哪位数据是错误的。问题是当我读入消息时消息总是空的。我认为这是因为在读取流之前总是抛出一个 filenotfound 异常。我对吗?我也尝试阅读错误流,但这总是空的。这是一个片段:

    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();
    }
    }
4

3 回答 3

3

所以只是为了跟进这个问题,这就是我解决它的方法:

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...
}

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

于 2010-10-29T11:28:46.700 回答
0

尝试将内容类型请求属性设置为"application/x-www-form-urlencoded"

此链接中也提到了相同的内容:http: //developers.sun.com/mobility/midp/ttips/HTTPPost/

The Content-Length and Content-Type headers are critical because they tell the web server how many bytes of data to expect, and what kind, identified by a MIME type.

In MIDP clients the two most popular MIME types are application/octet-stream, to send raw binary data, and application/x-www-form-urlencoded, to send name-value pairs

于 2010-09-28T04:23:19.587 回答
0

你能控制服务器吗?换句话说,您是否编写了在服务器上运行并侦听您尝试访问的端口的进程?

如果你这样做了,那么你也应该能够调试它并查看为什么你的进程返回 404。

如果您没有,请描述您的架构(HTTP 服务器、它调用以响应您的 HTTP(S) 请求的组件等),我们将从那里获取它。

在最简单的情况下,一个 HTTP 服务器是一个 Apache 服务器,将控制权交给一些 PHP 脚本,这意味着 Apache 无法将您的请求分配给任何东西。很可能是 Web 服务器配置错误。提供更多详细信息,我们将为您提供帮助。

于 2010-09-30T23:08:09.453 回答