Sunday, 4 March 2012

Executing a HTTP POST Request with HttpClient

This code executes a HTTP POST request with org.apache.http.client.HttpClient. Could be used in combination with "Non-Blocking Web Requests".


  • public void postData() {
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(POST_URL);
    
        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("Username", "test_user"));
            nameValuePairs.add(new BasicNameValuePair("Password", "123456"));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    
            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);
            
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
    } 

No comments:

Post a Comment