2012-09-24 171 views
0

我正在我的本地機器上運行tomcat servlet,並且使用向servlet發出發佈請求的應用程序運行Android模擬器。 POST的代碼如下(沒有例外等):通過android模擬器發送HTTP POST請求不起作用

 String strUrl = "http://10.0.2.2:8080/DeviceDiscoveryServer/server/devices/"; 
     Device device = Device.getUniqueInstance(); 

     urlParameters += URLEncoder.encode("user", "UTF-8") + "=" + URLEncoder.encode(device.getUser(), "UTF-8"); 
     urlParameters += "&" + URLEncoder.encode("port", "UTF-8") + "=" + URLEncoder.encode(new Integer(Device.PORT).toString(), "UTF-8"); 
     urlParameters += "&" + URLEncoder.encode("address", "UTF-8") + "=" + URLEncoder.encode(device.getAddress().getHostAddress(), "UTF-8"); 

     URL url = new URL(strUrl); 
     HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
     connection.setDoOutput(true); 
     connection.setRequestMethod("POST"); 

     OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream()); 
     wr.write(urlParameters); 
     wr.flush(); 
     wr.close(); 

無論何時執行此代碼,都不會調用該servlet。但是,如果我將請求的類型更改爲「GET」,並且不向輸出流寫入任何內容,則會調用該servlet並且一切正常。我只是沒有正確地開展POST或有其他一些錯誤?

+0

你應該將檢查你的servlet代碼。它應該接受POST請求。 –

+0

這個servlet的工作原理。看到下面,我找到了一個可行的解決方案。我不知道爲什麼。 –

回答

0

出於好奇,我試圖得到響應代碼爲我的請求:

int responseCode = connection.getResponseCode(); 
System.out.println(responseCode); 

這實際上提出的要求,經過和我200我檢查了我的Tomcat日誌和請求終獲處理。我猜想url.openConnection()並寫入OutputStream是不夠的。

1

試試下面的代碼,它可以幫助ü

 try 
{ 
    String argUrl = 
     ""; 

    String requestXml = ""; 
    URL url = new URL(argUrl); 
    URLConnection con = url.openConnection(); 
    System.out.println("STRING" + requestXml); 
    // specify that we will send output and accept input 
    con.setDoInput(true); 
    con.setDoOutput(true); 

    con.setConnectTimeout(20000); // long timeout, but not infinite 
    con.setReadTimeout(20000); 

    con.setUseCaches (false); 
    con.setDefaultUseCaches (false); 

    // tell the web server what we are sending 
    con.setRequestProperty ("Content-Type", "text/xml"); 

    OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream()); 
    writer.write(requestXml); 
    writer.flush(); 
    writer.close(); 

    // reading the response 
    InputStreamReader reader = new InputStreamReader(con.getInputStream()); 

    StringBuilder buf = new StringBuilder(); 
    char[] cbuf = new char[ 2048 ]; 
    int num; 

    while (-1 != (num=reader.read(cbuf))) 
    { 
     buf.append(cbuf, 0, num); 
    } 

    String result = buf.toString(); 
    System.err.println("\nResponse from server after POST:\n" + result); 
} 
catch(Throwable t) 
{ 
    t.printStackTrace(System.out); 
}