通过POST将参数发送到php文件并读取php文件的echo

时间:2014-04-27 20:47:12

标签: java php post echo

我将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文件回显的值?

1 个答案:

答案 0 :(得分:0)

您可以通过这种方式阅读帖子回复:

    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/