2012-12-28 89 views
0

我嘗試發送post請求,但webserver返回我沒有添加post-values。我花了很多時間試圖解決這個問題,但沒有結果。下面是代碼:Java http post:values arent added

public static String post(String url, String postParams) 
{ 
    URLConnection connection = null; 
    try 
    { 
     connection = initializeConnection(url); 
     connection.setDoOutput(true); 
     ((HttpURLConnection) connection).setRequestMethod("POST"); 
     connection.setRequestProperty("Content-Type", "text/xml"); 
     connection.setRequestProperty("Accept", "text/xml"); 
     connection.setUseCaches(false); 
     connection.setDoInput(true); 
     DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); 
     wr.write(postParams.getBytes()); 

     wr.flush(); 
     wr.close(); 

     // Get Response 
     InputStream is = connection.getInputStream(); 
     return inputStreamToString(is); 
    } 
    catch (Exception e) 
    { 
     e.printStackTrace(); 
     return null; 

    } 
} 

protected static HttpURLConnection initializeConnection(String stringUrl) 
{ 
    HttpURLConnection connection; 
    URL url = null; 
    try 
    { 
     url = new URL(stringUrl); 
    } 
    catch (MalformedURLException e1) 
    { 
     e1.printStackTrace(); 
    } 
    try 
    { 
     connection = (HttpURLConnection) url.openConnection(); 
     connection.setConnectTimeout(5000); 
    } 
    catch (Exception e) 
    { 
     e.printStackTrace(); 
     return null; 
    } 

    return connection; 
} 

public static String inputStreamToString(InputStream is) 
{ 
    BufferedReader r = new BufferedReader(new InputStreamReader(is)); 
    StringBuilder total = new StringBuilder(); 
    String line; 
    try 
    { 
     while ((line = r.readLine()) != null) 
     { 
      total.append(line); 
     } 
    } 
    catch (IOException e) 
    { 
     e.printStackTrace(); 
    } 
    return total.toString(); 
} 

我收到來自Web服務器的消息在那裏被告知沒有添加後的值。據我瞭解的代碼,值被添加。我卡住了。

+1

使用Wireshark或Fiddler檢查網絡層上的數據傳輸。 – burna

+0

在調試器中,您是否驗證過postParams包含數據,並在其上調用getBytes()的結果爲您提供數據? –

+0

檢查你是否在post post方法中獲得postParams ... 好像代碼沒問題... – Pratik

回答

0

調試'postParams'參數並檢查發送的內容。

+0

這是一條評論,而不是答案。 – Gimby

+0

我同意,但他還不能寫評論呢。 – Pr0gr4mm3r

1

原來,這一切我所要做的就是更換

connection.setRequestProperty("Content-Type", "text/xml"); 

connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 

如此簡單,因此花費的時間來清除出來... 順便說一句,我怎麼知道服務器需要這個頭文件?我認爲所有對請求必不可少的工作都將由java自動完成。

P.S.安裝小提琴幫助解決了這個問題,謝謝你。