【问题标题】:HttpsURLConnection Connection ProblemsHttpsURLConnection 连接问题
【发布时间】:2010-09-27 13:36:16
【问题描述】:

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

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

【问题讨论】:

    标签: java android httpurlconnection


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      尝试将 content-type 请求属性设置为"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

      【讨论】:

        【解决方案3】:

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

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

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

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

        【讨论】:

          猜你喜欢
          • 2013-03-14
          • 2014-06-11
          • 1970-01-01
          • 1970-01-01
          • 2011-01-11
          • 2013-05-29
          • 1970-01-01
          • 1970-01-01
          • 2023-03-16
          相关资源
          最近更新 更多