Domanda

I am sending NameValuePair parameters to a php file on my server and this php file echoes one of three string values.

I need to write code in Java to send these parameters to the PHP file via POST and also save the php file's echo response to a String.

This is what I have so far:

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;
}

I know I have the right lines of code for sending the POST parameters but how do I read the value the php file echoes corresponding to the given POST parameters?

È stato utile?

Soluzione

You can read the post response this way:

    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 = "";

See the full example here:

http://www.mkyong.com/java/apache-httpclient-examples/

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top