我正在将NameValuePair参数发送到服务器上的php文件,并且该php文件回显了三个字符串值之一。
我需要用Java编写代码,以通过POST将这些参数发送到PHP文件,并将php文件的echo响应保存到String。
这是我到目前为止所拥有的:
public String getStringFromUrl(String url, List<NameValuePair> params) throws IOException {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
HttpPost httpPost = new HttpPost(url);
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
String response2 = (String) response;
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return response;
}
我知道我具有发送POST参数的正确代码行,但是如何读取与给定POST参数相对应的php文件回显的值?
最佳答案
您可以通过以下方式阅读帖子回复:
HttpResponse response = client.execute(post);
System.out.println("Response Code : "
+ response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
在这里查看完整的示例:
http://www.mkyong.com/java/apache-httpclient-examples/