HttpsURLConnection连接问题

5

我有一个问题,涉及到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();
    }
    }
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...
}

看起来这样调用会产生一个带有消息的错误流。感谢您的建议!


0

尝试将 content-type 请求属性设置为 "application/x-www-form-urlencoded"

同样在此链接中提到: http://developers.sun.com/mobility/midp/ttips/HTTPPost/

Content-Length 和 Content-Type 标头非常重要,因为它们告诉 Web 服务器期望多少字节的数据以及什么类型的数据,由 MIME 类型标识。

在 MIDP 客户端中,最流行的两种 MIME 类型是 application/octet-stream(用于发送原始二进制数据)和 application/x-www-form-urlencoded(用于发送名称-值对)


0

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

如果是的话,那么你应该能够调试它,并查看为什么你的进程返回404。

如果不是的话,请描述你的架构(HTTP服务器、响应你的HTTP(S)请求的组件等),我们会从那里开始处理。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接