[Android教程] android的 Http工具类

来源:互联网 发布:教师资格考试 知乎 编辑:程序博客网 时间:2024/06/14 16:08
android的HttpClient实现简单的get和post请求
  1. /**
  2. * Http工具类
  3. */
  4. public class HttpUtil {
  5. // 创建HttpClient对象
  6. public static HttpClient httpClient = new DefaultHttpClient();
  7. public static final String BASE_URL = "";
  8. http://m.hwjbyby.com/nxby/dnlc/281.html
  9. /**
  10. * get请求
  11. *
  12. * @param url
  13. * 发送请求的URL
  14. * @return 服务器响应字符串
  15. * @throws Exception
  16. */
  17. public static String doGet(String url) throws Exception {
  18. // 创建HttpGet对象。
  19. HttpGet get = new HttpGet(url);
  20. // 发送GET请求
  21. HttpResponse httpResponse = httpClient.execute(get);
  22. // 如果服务器成功地返回响应
  23. if (httpResponse.getStatusLine().getStatusCode() == 200) {
  24. // 获取服务器响应字符串
  25. HttpEntity entity = httpResponse.getEntity();
  26. InputStream content = entity.getContent();
  27. return convertStreamToString(content);
  28. }
  29. return null;
  30. }
  31. /**
  32. * post请求
  33. *
  34. * @param url
  35. * 发送请求的URL
  36. * @param params
  37. * 请求参数
  38. * @return 服务器响应字符串
  39. * @throws Exception
  40. */http://m.hwjbyby.com/nxby/lcxby/282.html
  41. public static String doPost(String url, Map<String, String> rawParams)
  42. throws Exception {
  43. // 创建HttpPost对象。
  44. HttpPost post = new HttpPost(url);
  45. // 如果传递参数个数比较多的话可以对传递的参数进行封装
  46. List<NameValuePair> params = new ArrayList<NameValuePair>();
  47. for (String key : rawParams.keySet()) {
  48. // 封装请求参数
  49. params.add(new BasicNameValuePair(key, rawParams.get(key)));
  50. }
  51. // 设置请求参数
  52. post.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
  53. // 发送POST请求
  54. HttpResponse httpResponse = httpClient.execute(post);
  55. // 如果服务器成功地返回响应
  56. if (httpResponse.getStatusLine().getStatusCode() == 200) {
  57. // 获取服务器响应字符串
  58. HttpEntity entity = httpResponse.getEntity();
  59. InputStream content = entity.getContent();
  60. return convertStreamToString(content);
  61. }
  62. return null;
  63. }
  64. /**
  65. * 获取服务器的响应,转换为字符串
  66. */
  67. private static String convertStreamToString(InputStream is) {
  68. BufferedReader reader = new BufferedReader(new InputStreamReader(is));
  69. StringBuilder sb = new StringBuilder();
  70. String line = null;
  71. try {
  72. while ((line = reader.readLine()) != null) {
  73. sb.append(line);
  74. }
  75. } catch (IOException e) {
  76. e.printStackTrace();
  77. } finally {
  78. try {
  79. is.close();
  80. } catch (IOException e) {
  81. e.printStackTrace();
  82. }http://m.hwjbyby.com/nxby/lcxby/282.html
  83. }m.hwjbyby.com/nxby
  84. return sb.toString();
  85. }
  86. }
0 0
原创粉丝点击