HttpClientUtils.java 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package com.easemob.easeui.interUtil;
  2. import android.util.Log;
  3. import org.apache.http.HttpResponse;
  4. import org.apache.http.client.HttpClient;
  5. import org.apache.http.client.entity.UrlEncodedFormEntity;
  6. import org.apache.http.client.methods.HttpGet;
  7. import org.apache.http.client.methods.HttpPost;
  8. import org.apache.http.client.utils.URLEncodedUtils;
  9. import org.apache.http.impl.client.DefaultHttpClient;
  10. import org.apache.http.message.BasicNameValuePair;
  11. import org.apache.http.util.EntityUtils;
  12. import java.util.List;
  13. public class HttpClientUtils {
  14. public static String get(String baseUrl,List<BasicNameValuePair> params ) {
  15. // 对参数编码
  16. String param = URLEncodedUtils.format(params, "UTF-8");
  17. // 将URL与参数拼接 发送请求
  18. HttpGet getMethod = new HttpGet(baseUrl + "?" + param);
  19. //创建默认客户端的实例
  20. HttpClient httpClient = new DefaultHttpClient();
  21. try {
  22. //执行get请求返回 响应对象
  23. HttpResponse response = httpClient.execute(getMethod); // 发起GET请求
  24. //获取响应状态码并判断
  25. if(response.getStatusLine().getStatusCode() == 200){
  26. System.out.println("连接成功");
  27. return EntityUtils.toString(response.getEntity(),"utf-8");
  28. }
  29. } catch (Exception e) {
  30. e.printStackTrace();
  31. return null;
  32. }
  33. return null;
  34. }
  35. public static String post(String baseUrl,List<BasicNameValuePair> params){
  36. try {
  37. HttpPost postMethod = new HttpPost(baseUrl);
  38. //设置参数的类型
  39. postMethod.setEntity(new UrlEncodedFormEntity(params, "utf-8")); //将参数填入POST Entity中
  40. HttpClient httpClient = new DefaultHttpClient();
  41. HttpResponse response = httpClient.execute(postMethod); //执行POST方法
  42. if(response.getStatusLine().getStatusCode() == 200){
  43. return EntityUtils.toString(response.getEntity(),"utf-8");
  44. }
  45. } catch (Exception e) {
  46. e.printStackTrace();
  47. return null;
  48. }
  49. return null;
  50. }
  51. }