Skip to content

Instantly share code, notes, and snippets.

@cassc
Created April 17, 2014 04:30
Show Gist options
  • Save cassc/10952910 to your computer and use it in GitHub Desktop.
Save cassc/10952910 to your computer and use it in GitHub Desktop.
Use shared HttpClient instance for multiple requests
package concurrentRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class CookieHttpRequestTest {
public static void main(String[] args) throws ClientProtocolException, IOException {
HttpClient httpClient = new DefaultHttpClient();
getJsonByPost(httpClient,new HashMap<String, String>(), "http://localhost:8080/account/login.do?username=onse&surname=two&firstname=three&password=pwd");
getJsonByPost(httpClient,new HashMap<String, String>(), "http://localhost:8080/account/get.do");
}
public static String getJsonByPost(HttpClient httpClient, Map<String, String> paramMap, String resUrl) throws ClientProtocolException, IOException {
String result = null;
HttpPost httpRequest = new HttpPost(resUrl);
List<NameValuePair> params = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> param : paramMap.entrySet()) {
params.add(new BasicNameValuePair(param.getKey(), param.getValue()));
}
httpRequest.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
HttpEntity httpEntity = new UrlEncodedFormEntity(params, "UTF-8");
httpRequest.setEntity(httpEntity);
HttpResponse httpResponse = httpClient.execute(httpRequest);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result = EntityUtils.toString(httpResponse.getEntity());
System.out.println(result);
return result;
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment