使用StringEntity在Android中发送POST请求?

问题描述 投票:0回答:1

我在2个程序中使用完全相同的代码,但POST数据的存储除外。在第一种方法(工作的方法)我使用NameValuePair,而在另一种方法中,我使用StringEntity(不起作用,但我也不使用任何编码)。我不使用编码的原因是因为它完全弄乱了我的String。具有StringEntity的代码将无法工作...这是代码:

public static String sendNamePostRequest(String urlString, String nameField) {

    HttpClient client = new DefaultHttpClient();

    HttpPost post = new HttpPost(urlString);

    StringBuffer sb = new StringBuffer();

    try {

        post.setEntity(new StringEntity(
                "__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=%2FwEPDwULLTE3NDM5MzMwMzRkZA%3D%3D&__EVENTVALIDATION=%2FwEWBAL%2B%2B4CfBgK52%2BLYCQK1gpH7BAL0w%2FPHAQ%3D%3D&_nameTextBox=John&_zoekButton=Zoek&numberOfLettersField=3"));

        HttpResponse response = client.execute(post);
        HttpEntity entity = response.getEntity();

        BufferedReader br = new BufferedReader(new InputStreamReader(
                entity.getContent()));
        String in = "";

        while ((in = br.readLine()) != null) {
            sb.append(in + "\n");
        }

        br.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

    return sb.toString();
}

此代码确实发送请求(使用wireshark嗅探以检查),但不返回相应的HTML数据。这可能是什么原因?

android parsing http-post
1个回答
0
投票

而不是使用:

HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();

BufferedReader br = new BufferedReader(new InputStreamReader(
                entity.getContent()));

删除HttpEntity entity = response.getEntity();并执行此操作:

HttpResponse response = client.execute(post);
BufferedReader br = new BufferedReader(new InputStreamReader(
                response.getEntity().getContent(), "UTF-8"));

对于NameValuePair,请检查this link

© www.soinside.com 2019 - 2024. All rights reserved.