HTTP POST + ANDROID没有获得响应!

时间:2011-01-21 08:36:14

标签: android post

我正在使用PHP进行Web服务。我发布参数并从服务器获取数据。它适用于少量数据。

我有一个测试服务,返回10 xml记录,运行良好。具有所有160 xml记录的相同Web服务不会获取数据。

我粘贴了下面的代码.. 数据量方面是否有任何限制,还是需要传递任何其他参数?

public void LoadNews(String Url, List<NameValuePair> nvp) {
    InputStream ins = null;
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(Url);
    httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");

    try {
        // Add your data
        List<NameValuePair> nameValuePairs = nvp;
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);

        ins = response.getEntity().getContent();
        BufferedInputStream bis = new BufferedInputStream(ins);
        ByteArrayBuffer baf = new ByteArrayBuffer(1024);

        int current = 0;
        while ((current = bis.read()) != -1) {
            baf.append((byte) current);
        }
        String response = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
                + new String(baf.toByteArray());
    } catch (ClientProtocolException e) {
        Log.e(CommonFunctions.LOGTAG, "ClientProtocolException");
    } catch (IOException e) {
        Log.e(CommonFunctions.LOGTAG, "IOException");
    }

我使用Firefox + Poster Addon测试了相同的web服务,它的工作正常.. XML给CDATA作出回应。

1 个答案:

答案 0 :(得分:0)

这不是答案,而是建议 - 使用BasicResponseHandler检索HTTP内容。它节省了所有的流媒体/缓冲废话! (即大多数try条款)

String response = httpclient.execute(httppost, new BasicResponseHandler());

为了更清楚:

public void LoadNews(String Url, List<NameValuePair> nvp) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(Url);
    httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");

    try {
        // Add your data
        List<NameValuePair> nameValuePairs = nvp;
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        String response = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + 
            httpclient.execute(httppost, new BasicResponseHandler());

        /* ... do stuff with response ... */
    } catch (ClientProtocolException e) {
        Log.e(CommonFunctions.LOGTAG, "ClientProtocolException");
    } catch (IOException e) {
        Log.e(CommonFunctions.LOGTAG, "IOException");
    }
}

作为附录,您应该手动添加XML标头 - 这应该由您正在使用的Web服务在文档中返回。