[Android教程] android的 Http工具类

本文介绍了一个用于Android平台的HTTP工具类,该工具类通过HttpClient实现了GET和POST请求的方法。其中包括了如何构造请求、发送请求并从服务器获取响应的详细过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值