JAL-1028 utilities package for accessing synchronous web services with apache's HTTP...
[jalview.git] / src / jalview / ws / HttpClientUtils.java
1 package jalview.ws;
2
3 import java.io.BufferedReader;
4 import java.io.IOException;
5 import java.io.InputStreamReader;
6 import java.util.List;
7
8 import org.apache.http.HttpEntity;
9 import org.apache.http.HttpResponse;
10 import org.apache.http.NameValuePair;
11 import org.apache.http.client.ClientProtocolException;
12 import org.apache.http.client.HttpClient;
13 import org.apache.http.client.entity.UrlEncodedFormEntity;
14 import org.apache.http.client.methods.HttpPost;
15 import org.apache.http.impl.client.DefaultHttpClient;
16
17 /**
18  * Helpful procedures for working with services via HTTPClient
19  * @author jimp
20  *
21  */
22 public class HttpClientUtils
23 {
24   /**
25    * do a minimal HTTP post with URL-Encoded parameters passed in the Query
26    * string
27    * 
28    * @param postUrl
29    * @param vals
30    * @return Reader containing content, if any, or null if no entity returned.
31    * @throws IOException
32    * @throws ClientProtocolException
33    * @throws Exception
34    */
35   public static BufferedReader doHttpUrlPost(String postUrl,
36           List<NameValuePair> vals) throws ClientProtocolException,
37           IOException
38   {
39     HttpClient httpclient = new DefaultHttpClient();
40     HttpPost httppost = new HttpPost(postUrl);
41     UrlEncodedFormEntity ue = new UrlEncodedFormEntity(vals, "UTF-8");
42     httppost.setEntity(ue);
43     HttpResponse response = httpclient.execute(httppost);
44     HttpEntity resEntity = response.getEntity();
45
46     if (resEntity != null)
47     {
48       BufferedReader r = new BufferedReader(new InputStreamReader(
49               resEntity.getContent()));
50       return r;
51     }
52     else
53     {
54       return null;
55     }
56   }
57
58 }