0

所以我有2个代码应该做同样的事情。然而,我在 Android 上使用的那个返回错误的 HTML 数据。股票 Java 一在发送请求后返回正确的数据。我这里有两个代码。你能告诉我(即使我给了 ANDROID 互联网许可)为什么 Android 不工作,而股票 Java 工作?这是安卓代码:

编辑:我找到了修复。如果要使用 StringEntity 将这样的字符串发送到服务器,则必须将内容设置为 application/x-www-form-urlencoded。我编辑了我的代码以显示这一点:

public static String sendNamePostRequest(String urlString) {

    HttpClient client = new DefaultHttpClient();

    HttpPost post = new HttpPost(urlString);

    StringBuffer sb = new StringBuffer();

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

        se.setContent("application/x-www-form-urlencoded");

        post.setEntity();

        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();
}

这是股票 Java 代码:

public String sendNamePostRequest(String urlString) {

    StringBuffer sb = null;

    try {
        String data = "__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=%2FwEPDwULLTE3NDM5MzMwMzRkZA%3D%3D&__EVENTVALIDATION=%2FwEWBAL%2B%2B4CfBgK52%2BLYCQK1gpH7BAL0w%2FPHAQ%3D%3D&_nameTextBox=John&_zoekButton=Zoek&numberOfLettersField=3";

        // String data = "";

        URL requestUrl = new URL(urlString);

        HttpURLConnection conn = (HttpURLConnection) requestUrl
                .openConnection();

        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

        dos.writeBytes(data);
        dos.flush();

        BufferedReader br = new BufferedReader(new InputStreamReader(
                conn.getInputStream()));

        String in = "";
        sb = new StringBuffer();

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

        dos.close();
        br.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
    return sb.toString();
}
4

2 回答 2

0

您可以使用 NameValuePair 和 UrlEncodedFormEntity:

List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
nvps.add(new BasicNameValuePair(KEY1, VALUE1));
nvps.add(new BasicNameValuePair(KEY2, VALUE2));
UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(nvps,HTTP.UTF_8);
post.setEntity(p_entity);
于 2012-04-05T04:19:38.183 回答
0

如果数据正在到达服务器,您可能想查看那里发生了什么(日志、错误、异常等)。除此之外:

  • use can use HttpURLConnection,所以你可以有完全相同的代码
  • 对于 HttpClient,不确定您是否自己编码实体。用于NameValuePair设置参数,HttpClient 将为您(正确)编码。
于 2012-04-05T03:43:25.470 回答