Guest User

Untitled

a guest
Jan 23rd, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. package your_packagename_here;
  2.  
  3. import java.io.ByteArrayOutputStream;
  4. import java.io.IOException;
  5. import java.io.UnsupportedEncodingException;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8.  
  9. import org.apache.http.HttpResponse;
  10. import org.apache.http.HttpStatus;
  11. import org.apache.http.NameValuePair;
  12. import org.apache.http.client.ClientProtocolException;
  13. import org.apache.http.client.HttpClient;
  14. import org.apache.http.client.entity.UrlEncodedFormEntity;
  15. import org.apache.http.client.methods.HttpGet;
  16. import org.apache.http.client.methods.HttpPost;
  17. import org.apache.http.client.methods.HttpUriRequest;
  18. import org.apache.http.client.utils.URLEncodedUtils;
  19. import org.apache.http.impl.client.DefaultHttpClient;
  20. import org.apache.http.message.BasicNameValuePair;
  21.  
  22. public class EasyHttpClient {
  23.  
  24. protected String url;
  25. protected HttpClient httpClient;
  26. protected List<NameValuePair> params = new ArrayList<NameValuePair>(1);
  27.  
  28. public EasyHttpClient(String url) {
  29. this.httpClient = new DefaultHttpClient();
  30. this.url = url;
  31. }
  32.  
  33. public void addParam(String key, String value) {
  34. this.params.add(new BasicNameValuePair(key, value));
  35. }
  36.  
  37. public String doGet() throws ClientProtocolException, IOException {
  38. String queries = URLEncodedUtils.format(this.params, "UTF-8");
  39. HttpGet httpGet = new HttpGet(this.url + "?" + queries);
  40.  
  41. return this.doHttpRequest(httpGet);
  42. }
  43.  
  44. public String doPost() throws UnsupportedEncodingException, ClientProtocolException, IOException {
  45. UrlEncodedFormEntity entry = new UrlEncodedFormEntity(this.params);
  46. HttpPost httpPost = new HttpPost(this.url);
  47. httpPost.setEntity(entry);
  48. return this.doHttpRequest(httpPost);
  49. }
  50.  
  51. protected String doHttpRequest(HttpUriRequest request) throws ClientProtocolException, IOException {
  52. String responseText = null;
  53. HttpResponse response = this.httpClient.execute(request);
  54.  
  55. ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
  56. response.getEntity().writeTo(byteArrayOutputStream);
  57.  
  58. if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
  59. responseText = byteArrayOutputStream.toString();
  60. }
  61. byteArrayOutputStream.close();
  62.  
  63. return responseText;
  64. }
  65. }
Add Comment
Please, Sign In to add comment