我在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数据。这可能是什么原因?
答案 0 :(得分: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