在Android上发送 HTTP 请求的方式一般有两种, HttpURLConnection 和 HttpClient,关于HttpURLConnection的使用方法能够參考HTTP之利用HttpURLConnection訪问网页,这里仅仅介绍HttpClient发送POST与GET请求的使用方法。

HttpClient 是 Apache 提供的 HTTP 网络訪问接口, 使用须要注意下面几点:

首先看下发送GET请求:

1.声明一下网络权限,改动AndroidManifest.xml中的代码:

  1. <uses-permission android:name="android.permission.INTERNET" />

2.HttpClient 是一个接口,因此无法创建它的实例, 通常情况下都会创建一个 DefaultHttpClient 的实例

  1. HttpClient httpClient = new DefaultHttpClient();

3.创建一个 HttpGet 对象,并传入目标的网络地址, 然后调用 HttpClient 的 execute()方法就可以:

  1. HttpGet httpGet = new HttpGet("http://www.baidu.com");
  2. httpClient.execute(httpGet);

4.执行execute()方法之后会返回一个HttpResponse对象, server所返回的全部信息就会包括在这里面, 因此我们能够实例化一个HttpResponse对象来接收execute()方法返回的结果:

  1. HttpResponse response = httpClient.execute(httpGet);

5.推断server返回的状态码,假设等于 200就说明请求和响应都成功了:

  1. if(httpResponse.getStatusLine().getStatusCode() == 200) {
  2. // 请求和响应都成功了
  3. }

6.在上面的if推断里面调用getEntity()方法获取到一个HttpEntity实例,然后再用EntityUtils.toString()这个静态方法将 HttpEntity 转换成字符串就可以获取:

  1. if(httpResponse.getStatusLine().getStatusCode() == 200) {
  2. HttpEntity entity = response.getEntity();
  3. String content = EntityUtils.toString(entity);
  4. }

下面以一个样例获取一个ip的归属地和运营商(结合了解析JSON。Handler异步更新机制。HttpClient发送GET请求)。这里直接给出MianActivity中的代码例如以下:

  1. package com.example.androidstudyhttpclient;
  2. import java.io.IOException;
  3. import org.apache.http.HttpEntity;
  4. import org.apache.http.HttpResponse;
  5. import org.apache.http.HttpStatus;
  6. import org.apache.http.client.ClientProtocolException;
  7. import org.apache.http.client.HttpClient;
  8. import org.apache.http.client.methods.HttpGet;
  9. import org.apache.http.impl.client.DefaultHttpClient;
  10. import org.apache.http.util.EntityUtils;
  11. import org.json.JSONException;
  12. import org.json.JSONObject;
  13. import com.example.androidstudypostget.R;
  14. import android.app.Activity;
  15. import android.os.Bundle;
  16. import android.os.Handler;
  17. import android.os.Message;
  18. import android.util.Log;
  19. import android.view.View;
  20. import android.view.View.OnClickListener;
  21. import android.widget.Button;
  22. import android.widget.TextView;
  23. public class MainActivity extends Activity implements OnClickListener{
  24. protected static final int SHOW_RESPONSE = 0;
  25. private TextView textview;
  26. private Button button1;
  27. private Button button2;
  28. @Override
  29. protected void onCreate(Bundle savedInstanceState) {
  30. super.onCreate(savedInstanceState);
  31. setContentView(R.layout.activity_main);
  32. textview = (TextView) findViewById(R.id.tv);
  33. button1 = (Button) findViewById(R.id.bt1);
  34. button2 = (Button) findViewById(R.id.bt2);
  35. button1.setOnClickListener(this);
  36. button2.setOnClickListener(this);
  37. }
  38. public Handler handler = new Handler(){
  39. public void handleMessage(Message msg){
  40. switch(msg.what){
  41. case SHOW_RESPONSE:
  42. String response = (String) msg.obj;
  43. try {
  44. JSONObject jsobject1 = new JSONObject(response);
  45. String data = jsobject1.getString("data");
  46. JSONObject jsobject2 = new JSONObject(data);
  47. String region = jsobject2.getString("region");
  48. String isp = jsobject2.getString("isp");
  49. textview.setText("归属地:"+region+" 运营商:"+isp);
  50. } catch (JSONException e) {
  51. e.printStackTrace();
  52. }
  53. }
  54. }
  55. };
  56. public void sendget(){
  57. new Thread(new Runnable() {
  58. @Override
  59. public void run() {
  60. final String url = "http://ip.taobao.com/service/getIpInfo.php?
  61. ip=220.181.57.217";
  62. HttpClient getClient = new DefaultHttpClient();
  63. HttpGet httpGet = new HttpGet(url);
  64. HttpResponse response;
  65. try {
  66. response = getClient.execute(httpGet);
  67. if(response.getStatusLine().getStatusCode() ==200){
  68. HttpEntity entity = response.getEntity();
  69. String content = EntityUtils.toString(entity);
  70. Message message = new Message();
  71. message.what = SHOW_RESPONSE;
  72. message.obj = content;
  73. handler.sendMessage(message);
  74. }
  75. } catch (ClientProtocolException e) {
  76. e.printStackTrace();
  77. } catch (IOException e) {
  78. e.printStackTrace();
  79. }
  80. }
  81. }).start();
  82. }
  83. @Override
  84. public void onClick(View v) {
  85. switch(v.getId()){
  86. case R.id.bt1:
  87. sendget();
  88. break;
  89. case R.id.bt2:
  90. break;
  91. default:
  92. break;
  93. }
  94. }
  95. }

执行后点击httpGet按钮截图例如以下:

接下来看下发送POST请求:

1.声明一下网络权限,改动AndroidManifest.xml中的代码:

  1. <uses-permission android:name="android.permission.INTERNET" />

2.HttpClient 是一个接口,因此无法创建它的实例, 通常情况下都会创建一个 DefaultHttpClient 的实例

  1. HttpClient httpClient = new DefaultHttpClient();

3.创建一个HttpPost 对象, 并传入目标的网络地址(比方Servlet用于接收POST请求的地址)

  1. final String url = "xxx";
  2. HttpPost httpPost = new HttpPost(url);

4.通过一个NameValuePair集合来存放待提交的參数, 并将这个參数集合传入到一个UrlEncodedFormEntity中, 然后调用 HttpPost的setEntity()方法将构建好的 UrlEncodedFormEntity传入:

  1. List<NameValuePair> params = new ArrayList<NameValuePair>();
  2. params.add(new BasicNameValuePair("username", "admin"));
  3. params.add(new BasicNameValuePair("password", "123456"));
  4. UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "utf-8");
  5. httpPost.setEntity(entity);

5.调用 HttpClient 的 execute()方法,并将 HttpPost 对 象传入:

  1. httpClient.execute(httpPost);

6.执行execute()方法之后会返回一个HttpResponse对象, server所返回的全部信息就会包括在这里面, 因此我们能够实例化一个HttpResponse对象来接收execute()方法返回的结果:

  1. HttpResponse response = httpClient.execute(httpGet);

7.推断server返回的状态码,假设等于200就说明请求和响应都成功了:

  1. if(httpResponse.getStatusLine().getStatusCode() == 200) {
  2. // 请求和响应都成功了
  3. }

8.在上面的if推断里面调用getEntity()方法获取到一个HttpEntity实例,然后再用EntityUtils.toString()这个静态方法将 HttpEntity 转换成字符串就可以获取:

  1. if(httpResponse.getStatusLine().getStatusCode() == 200) {
  2. HttpEntity entity = response.getEntity();
  3. String content = EntityUtils.toString(entity);
  4. }

下面给出提供HttpClient发送POST数据到serverMainActivity代码:

  1. package com.example.androidstudyhttpclient;
  2. import java.io.IOException;
  3. import java.io.UnsupportedEncodingException;
  4. import java.util.ArrayList;
  5. import java.util.List;
  6. import org.apache.http.HttpEntity;
  7. import org.apache.http.HttpResponse;
  8. import org.apache.http.HttpStatus;
  9. import org.apache.http.NameValuePair;
  10. import org.apache.http.client.ClientProtocolException;
  11. import org.apache.http.client.HttpClient;
  12. import org.apache.http.client.entity.UrlEncodedFormEntity;
  13. import org.apache.http.client.methods.HttpGet;
  14. import org.apache.http.client.methods.HttpPost;
  15. import org.apache.http.impl.client.DefaultHttpClient;
  16. import org.apache.http.message.BasicNameValuePair;
  17. import org.apache.http.util.EntityUtils;
  18. import org.json.JSONException;
  19. import org.json.JSONObject;
  20. import com.example.androidstudypostget.R;
  21. import android.app.Activity;
  22. import android.os.Bundle;
  23. import android.os.Handler;
  24. import android.os.Message;
  25. import android.util.Log;
  26. import android.view.View;
  27. import android.view.View.OnClickListener;
  28. import android.widget.Button;
  29. import android.widget.TextView;
  30. public class MainActivity extends Activity implements OnClickListener{
  31. protected static final int SHOW_RESPONSE = 0;
  32. protected static final int SHOW_RESPONSE2 = 1;
  33. private TextView textview;
  34. private Button button1;
  35. private Button button2;
  36. @Override
  37. protected void onCreate(Bundle savedInstanceState) {
  38. super.onCreate(savedInstanceState);
  39. setContentView(R.layout.activity_main);
  40. textview = (TextView) findViewById(R.id.tv);
  41. button1 = (Button) findViewById(R.id.bt1);
  42. button2 = (Button) findViewById(R.id.bt2);
  43. button1.setOnClickListener(this);
  44. button2.setOnClickListener(this);
  45. }
  46. public Handler handler = new Handler(){
  47. public void handleMessage(Message msg){
  48. switch(msg.what){
  49. case SHOW_RESPONSE2:
  50. String response2 = (String) msg.obj;
  51. textview.setText(response2);
  52. }
  53. }
  54. };
  55. public void sendpost(){
  56. new Thread(new Runnable() {
  57. public void run() {
  58. final String url = "http://192.168.51.103:8080/ServletDemo/servlet/HttpClientPostDemo";
  59. HttpClient postClient = new DefaultHttpClient();
  60. HttpPost httpPost = new HttpPost(url);
  61. List<NameValuePair> params = new ArrayList<NameValuePair>();
  62. params.add(new BasicNameValuePair("name", "geek"));
  63. params.add(new BasicNameValuePair("city", "shanghai"));
  64. UrlEncodedFormEntity entity;
  65. HttpResponse response;
  66. try {
  67. entity = new UrlEncodedFormEntity(params, "utf-8");
  68. httpPost.setEntity(entity);
  69. response = postClient.execute(httpPost);
  70. if(response.getStatusLine().getStatusCode()==200){
  71. HttpEntity entity2 = response.getEntity();
  72. String content = EntityUtils.toString(entity2);
  73. Message message = new Message();
  74. message.what = SHOW_RESPONSE2;
  75. message.obj = content;
  76. handler.sendMessage(message);
  77. }
  78. } catch (UnsupportedEncodingException e) {
  79. e.printStackTrace();
  80. } catch (ClientProtocolException e) {
  81. e.printStackTrace();
  82. } catch (IOException e) {
  83. e.printStackTrace();
  84. }
  85. }
  86. }).start();
  87. }
  88. @Override
  89. public void onClick(View v) {
  90. switch(v.getId()){
  91. case R.id.bt1:
  92. sendget();
  93. break;
  94. case R.id.bt2:
  95. sendpost();
  96. break;
  97. default:
  98. break;
  99. }
  100. }
  101. }

Servlet代码例如以下:

  1. import java.io.IOException;
  2. import java.io.PrintWriter;
  3. import javax.servlet.ServletException;
  4. import javax.servlet.http.HttpServlet;
  5. import javax.servlet.http.HttpServletRequest;
  6. import javax.servlet.http.HttpServletResponse;
  7. public class HttpClientPostDemo extends HttpServlet {
  8. public HttpClientPostDemo() {
  9. super();
  10. }
  11. public void destroy() {
  12. super.destroy();
  13. }
  14. public void doGet(HttpServletRequest request, HttpServletResponse response)
  15. throws ServletException, IOException {
  16. doPost(request,response);
  17. }
  18. public void doPost(HttpServletRequest request, HttpServletResponse response)
  19. throws ServletException, IOException {
  20. response.setContentType("text/html");
  21. String name = request.getParameter("name");
  22. String city = request.getParameter("city");
  23. PrintWriter out = response.getWriter();
  24. out.write("Name is:"+name+" City is"+city);
  25. out.flush();
  26. out.close();
  27. }
  28. public void init() throws ServletException {
  29. }
  30. }

执行后点击httpPost按钮截图例如以下:

Android笔记---使用HttpClient发送POST和GET请求的更多相关文章

  1. HttpClient发送get,post接口请求

    HttpClient发送get post接口请求/*  * post  * @param url POST地址 * @param data POST数据NameValuePair[] * @retur ...

  2. Java实现HttpClient发送GET、POST请求(https、http)

    1.引入相关依赖包 jar包下载:httpcore4.5.5.jar    fastjson-1.2.47.jar maven: <dependency> <groupId>o ...

  3. 网络相关系列之中的一个:Android中使用HttpClient发送HTTP请求

    一.HTTP协议初探: HTTP(Hypertext Transfer Protocol)中文 "超文本传输协议",是一种为分布式,合作式,多媒体信息系统服务,面向应用层的协议,是 ...

  4. Android中使用HttpClient发送Get请求

    这里要指定编码,不然服务器接收到的会是乱码的.

  5. 使用httpclient发送get或post请求

    HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的.最新的.功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建 ...

  6. HttpClient发送Get和Post请求

    package JanGin.httpClient.demo; import java.io.IOException; import java.io.UnsupportedEncodingExcept ...

  7. java apache commons HttpClient发送get和post请求的学习整理(转)

    文章转自:http://blog.csdn.net/ambitiontan/archive/2006/01/06/572171.aspx HttpClient 是我最近想研究的东西,以前想过的一些应用 ...

  8. HttpClient 发送 HTTP、HTTPS 请求的简单封装

    import org.apache.commons.io.IOUtils; import org.apache.http.HttpEntity; import org.apache.http.Http ...

  9. [java,2018-01-16] HttpClient发送、接收 json 请求

    最近需要用到许多在后台发送http请求的功能,可能需要发送json和xml类型的数据. 就抽取出来写了一个帮助类: 首先判断发送的数据类型是json还是xml: import org.dom4j.Do ...

随机推荐

  1. 杭电oj2032、2040、2042、2054、2055

    2032  杨辉三角 #include <stdio.h> int main(){ ][],i,j,n; while(~scanf("%d",&n)){ ;i& ...

  2. (转)Python 操作 Windows 粘贴板

    转自: http://outofmemory.cn/code-snippet/3939/Python-operation-Windows-niantie-board Python 操作 Windows ...

  3. Linux/Android——input_handler之evdev (四) 【转】

    转自:http://blog.csdn.net/u013491946/article/details/72638919 版权声明:免责声明: 本人在此发文(包括但不限于汉字.拼音.拉丁字母)均为随意敲 ...

  4. TP5使用技巧

    1.fetchSql用于直接返回SQL而不是执行查询,适用于任何的CURD操作方法. 例如:$result = Db::table('think_user')->fetchSql(true)-& ...

  5. 实现如下语法的功能:var a = (5).plus(3).minus(6); //2

    从汤姆大叔的博客里看到了6个基础题目:本篇是第5题 - 实现如下语法的功能:var a = (5).plus(3).minus(6); //2 解题关键: 1.理解使用(5)和5的区别 2.构造函数原 ...

  6. Number Triangles

    题目描述 Consider the number triangle shown below. Write a program that calculates the highest sum of nu ...

  7. [BZOJ3569]DZY Loves Chinese II(随机化+线性基)

    3569: DZY Loves Chinese II Time Limit: 5 Sec  Memory Limit: 64 MBSubmit: 1515  Solved: 569[Submit][S ...

  8. kong流程学习

    kong: 根据Nginx的不同执行阶段,kong先执行初始化master和worker进程. init_by_lua_block { require 'resty.core' kong = requ ...

  9. 集合框架(04)HashMap扩展知识

    Map扩展知识 map集合被使用是具备映射关系 “bigclass”: “001”, ”zhangsan” “002”, ”lisi” “smallclass” : ”001”, “wangwu” : ...

  10. My first blog on cnBlogs!

    以后会长期更新自己的心得体会!以此锻炼自己,奋发向前.