Sunday, December 9, 2012

Httpclient : name value pair


Jar
httpclient-4.2.4.jar
httpcore-4.2.2.jar
httpmime-4.2.2.jar

Import package


import org.apache.http.Consts;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;



Send request to server

DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpost = new HttpPost(<url>);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair(<field>, <value>);
httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
HttpResponse response = httpclient.execute(httpost);

Request from proxy and need username and password

           httpclient.getCredentialsProvider().setCredentials(
                   new AuthScope("<proxy_host>", <proxy_port>),
                    new UsernamePasswordCredentials("<proxy_user>", "<proxy_password>"));
           HttpHost proxy = new HttpHost("("<proxy_host>", <proxy_port>);
           httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);


Response
Server response as below :
 <fieldName>=<value>&<fieldName>=<value>
Get response
Map<String, String> responseParams = parseResponse(response);
responseParams.get(<fieldName>") 

 
private static Map<String, String> parseResponse(HttpResponse response) throws IOException {
        Map<String, String> map = new HashMap<String, String>();
        String responseStr = getResponseContent(response);
        List<NameValuePair> responseParams = new ArrayList<NameValuePair>();
        URLEncodedUtils.parse(responseParams, new Scanner(responseStr), "UTF-8");
        for (NameValuePair nvp : responseParams) {
            map.put(nvp.getName(), nvp.getValue());
        }
        return map;
    }

    private static String getResponseContent(HttpResponse response) throws IOException {
        String result = "";
        InputStream is = response.getEntity().getContent();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = null;
        while ((line = br.readLine()) != null) {
            result += line;
        }
        return result;
    }

No comments:

Post a Comment