我正在为 android 制作应用程序,我需要使用 java 向 www.example.com 地址发出请求。问题是我需要发送 POST 参数,我一直在搜索一些信息,我发现了一些关于跨域或类似的东西。有人可以帮我处理请求并获得答案吗?
我尝试执行以下代码但不工作:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.example.com");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("param1", "val"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
解决方案:::::::::::::
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.example.com");
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("key", "val"));
postParameters.add(new BasicNameValuePair("key2", "val2"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
postParameters);
post.setEntity(formEntity);
HttpResponse response = client.execute(post);
//inputStreamToString method
String data = inputStreamToString(response.getEntity()
.getContent());
return data;
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
inputStreamToString 方法
private String inputStreamToString(InputStream is) {
String s = "";
String line = "";
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
s += line;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Return full string
return s;
}