通过android模拟器发送HTTP POST请求不起作用

时间:2012-09-24 03:35:34

标签: java android http tomcat android-emulator

我正在我的本地计算机上运行一个tomcat servlet,一个带有应用程序的Android模拟器向servlet发出一个post请求。 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还是有其他错误?

2 个答案:

答案 0 :(得分: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 );
}

答案 1 :(得分:0)

出于好奇,我尝试获取我的请求的响应代码:

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

这实际上让请求通过了,我得到了200.我检查了我的Tomcat日志,最终处理了请求。我想做url.openConnection()并写OutputStream是不够的。