代码之家  ›  专栏  ›  技术社区  ›  threadhack

Java GETIN流400错误

  •  2
  • threadhack  · 技术社区  · 16 年前

    当我使用JavaHTTPURLION联系Web服务时,它只返回一个400个坏请求(IOExExchange)。如何获取服务器返回的xml信息;它似乎不在连接的geterrorstream中,也不在任何异常信息中。

    当我对web服务运行以下php代码时:

    <?php
    
    $ch = curl_init();
    
    curl_setopt($ch, CURLOPT_URL, "https://www.myclientaddress.com/here/" );
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt($ch, CURLOPT_POST,1 );
    curl_setopt($ch, CURLOPT_POSTFIELDS,"username=ted&password=scheckler&type=consumer&id=123456789&zip=12345");
    
    $result=curl_exec ($ch);
    echo $result;
    ?>
    

    它返回以下内容:

    <?xml version="1.0" encoding="utf-8"?>
    <response>
        <status>failure</status>
        <errors>
            <error name="RES_ZIP">Zip code is not valid.</error>
            <error name="ZIP">Invalid zip code for residence address.</error>
        </errors>
    </response>
    

    所以我知道信息是存在的

    4 回复  |  直到 10 年前
        1
  •  2
  •   gpiazzese    10 年前

    如果尝试从连接中读取getinputstream(),httpurlconnection将返回filenotfoundexception,因此当状态代码等于或高于400时,应改用geterrorstream()。

    除此之外,请小心,因为成功状态代码不仅仅是200,甚至201、204等也经常被用作成功状态。

    下面是我如何管理它的一个例子

    // ... connection code code code ...
    
    // Get the response code 
    int statusCode = connection.getResponseCode();
    
    InputStream is = null;
    
    if (statusCode >= 200 && statusCode < 400) {
       // Create an InputStream in order to extract the response object
       is = connection.getInputStream();
    }
    else {
       is = connection.getErrorStream();
    }
    
    // ... callback/response to your handler....
    

    这样,您将能够在成功和错误情况下获得所需的响应。

    希望这有帮助!

        2
  •  1
  •   Community Mohan Dere    9 年前

    在这里找到答案: Read error response body in Java

    是我!

        3
  •  0
  •   Powerlord    16 年前

    如果服务器返回XML,并且将参数作为URL传递,为什么不使用只支持JAX-RS(Java的REST WebServices API)的库,例如 Apache CXF ?

    我知道它支持jax-rs,因为它有 chapter 在手册里。

        4
  •  0
  •   Akshay    13 年前

    我有同样的问题,在下面加上两行就解决了。

    httpconn.setrequestproperty(“连接”,“关闭”); setproperty(“http.keepalive”,“false”);