【发布时间】:2012-04-05 15:19:23
【问题描述】:
所以我有 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();
}
【问题讨论】:
-
指定“错误的 HTML 数据”是什么意思
-
这意味着我应该在它处理完请求后取回页面的HTML数据。普通的 Java 代码可以完美地做到这一点,但 Android 代码只是返回站点的 HTML 页面,而不考虑 POST 请求。 Wireshark 确实看到了来自 Android 和 Stock 方面的 POST,具有完全相同的数据字符串,但由于某种原因,他从 Java 发送的一个没有得到处理......
-
在 android 案例中,您可能需要告诉 StringEntity 将 content-type 设置为 application/x-www-form-urlencoded
-
我能想到你的实体字符串很麻烦。尝试使用
new StringEntity("yourString", HTTP.UTF_8)
标签: java android http post request