Using Http Post to fill a form with HttpClient.

1 vote · 1 comment

How to execute a Http Post to a form with HttpClient.

raw ·
copy
· download
public StringBuilder post(String url) { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); // Add your data (Var name, Var value) List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3); httppost.getParams().setParameter( CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE); nameValuePairs.add(new BasicNameValuePair("ageDay", "30")); nameValuePairs.add(new BasicNameValuePair("ageYear", "1959")); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Execute HTTP Post Request HttpResponse response = httpclient.execute(httppost); // Saves response String line = ""; StringBuilder result = new StringBuilder(); BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); while ((line = rd.readLine()) != null) { result.append(line); } rd.close(); return result; }
Add a comment

1 Comment

Ok, this is nice, but how can I add file. And let's say this post method returns json, so how can I get it.

Reply · June 14, 2012, 10:02 p.m.