2010-06-14 47 views
1

當我使用Java HttpUrlConnection聯繫Web服務時,它僅返回400錯誤請求(IOException)。如何獲取服務器返回的XML信息;它看起來不在連接的getErrorStream中,也不在任何異常信息中。Java getInputStream 400錯誤

當我運行鍼對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> 

,所以我知道的信息存在

回答

0

如果服務器返回XML,並將參數作爲url傳遞,爲什麼不僅僅使用支持JAX-RS(Java的REST webservices API)的庫,如Apache CXF

我知道它支持JAX-RS,因爲它在手冊中有chapter

+0

我沒有參與系統設計,所以我無法回答。它也取決於客戶端,有些返回XML返回文本。無論如何,連接支持不僅僅是捕獲原始回報? – threadhack 2010-06-14 15:24:55

0

我有同樣的問題,並添加下面兩行解決它。

httpConn.setRequestProperty(「Connection」,「Close」); System.setProperty(「http.keepAlive」,「false」);

1

HttpURLConnection的返回FileNotFoundException異常,如果您嘗試讀取從連接中的getInputStream(),所以你應該使用getErrorStream()時的狀態代碼等於或高於此比400

更多,請小心由於成功狀態代碼不僅僅是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.... 

這樣一個例子,你將能夠獲得成功和錯誤的情況下所需要的響應。

希望這會有所幫助!