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

用户名

我正在将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/

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章