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

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

首先看下发送GET请求:

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

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

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

HttpClient httpClient = new DefaultHttpClient();

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

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

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

HttpResponse response = httpClient.execute(httpGet);

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

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

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

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

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

package com.example.androidstudyhttpclient;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.androidstudypostget.R;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView; public class MainActivity extends Activity implements OnClickListener{
protected static final int SHOW_RESPONSE = 0;
private TextView textview;
private Button button1;
private Button button2; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview = (TextView) findViewById(R.id.tv);
button1 = (Button) findViewById(R.id.bt1);
button2 = (Button) findViewById(R.id.bt2);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
} public Handler handler = new Handler(){
public void handleMessage(Message msg){
switch(msg.what){
case SHOW_RESPONSE:
String response = (String) msg.obj;
try {
JSONObject jsobject1 = new JSONObject(response);
String data = jsobject1.getString("data");
JSONObject jsobject2 = new JSONObject(data);
String region = jsobject2.getString("region");
String isp = jsobject2.getString("isp");
textview.setText("归属地:"+region+" 运营商:"+isp);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}; public void sendget(){
new Thread(new Runnable() {
@Override
public void run() {
final String url = "http://ip.taobao.com/service/getIpInfo.php? ip=220.181.57.217";
HttpClient getClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response;
try {
response = getClient.execute(httpGet);
if(response.getStatusLine().getStatusCode() ==200){
HttpEntity entity = response.getEntity();
String content = EntityUtils.toString(entity);
Message message = new Message();
message.what = SHOW_RESPONSE;
message.obj = content;
handler.sendMessage(message);
} } catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.bt1:
sendget();
break;
case R.id.bt2:
break;
default:
break;
}
}
}

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

接下来看下发送POST请求:

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

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

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

HttpClient httpClient = new DefaultHttpClient();

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

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

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

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

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

httpClient.execute(httpPost);

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

HttpResponse response = httpClient.execute(httpGet);

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

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

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

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

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

package com.example.androidstudyhttpclient;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.androidstudypostget.R;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView; public class MainActivity extends Activity implements OnClickListener{
protected static final int SHOW_RESPONSE = 0;
protected static final int SHOW_RESPONSE2 = 1;
private TextView textview;
private Button button1;
private Button button2; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview = (TextView) findViewById(R.id.tv);
button1 = (Button) findViewById(R.id.bt1);
button2 = (Button) findViewById(R.id.bt2);
button1.setOnClickListener(this);
button2.setOnClickListener(this); } public Handler handler = new Handler(){
public void handleMessage(Message msg){
switch(msg.what){ case SHOW_RESPONSE2:
String response2 = (String) msg.obj;
textview.setText(response2);
}
}
}; public void sendpost(){
new Thread(new Runnable() {
public void run() {
final String url = "http://192.168.51.103:8080/ServletDemo/servlet/HttpClientPostDemo";
HttpClient postClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", "geek"));
params.add(new BasicNameValuePair("city", "shanghai"));
UrlEncodedFormEntity entity;
HttpResponse response;
try {
entity = new UrlEncodedFormEntity(params, "utf-8");
httpPost.setEntity(entity);
response = postClient.execute(httpPost); if(response.getStatusLine().getStatusCode()==200){
HttpEntity entity2 = response.getEntity();
String content = EntityUtils.toString(entity2);
Message message = new Message();
message.what = SHOW_RESPONSE2;
message.obj = content;
handler.sendMessage(message); } } catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} }
}).start();
} @Override
public void onClick(View v) {
switch(v.getId()){
case R.id.bt1:
sendget();
break;
case R.id.bt2:
sendpost();
break;
default:
break;
}
}
}

Servlet代码例如以下:

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class HttpClientPostDemo extends HttpServlet { public HttpClientPostDemo() {
super();
} public void destroy() {
super.destroy();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
String name = request.getParameter("name");
String city = request.getParameter("city");
PrintWriter out = response.getWriter();
out.write("Name is:"+name+" City is"+city);
out.flush();
out.close();
}
public void init() throws ServletException {
}
}

执行后点击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. 用户空间缺页异常pte_handle_fault()分析--(上)【转】

    转自:http://blog.csdn.net/vanbreaker/article/details/7881206 版权声明:本文为博主原创文章,未经博主允许不得转载. 前面简单的分析了内核处理用户 ...

  2. glxgears刷新只有60FPS解决办法

    问题原因在于屏幕的垂直同步刷新率的限制,解决办法是关闭垂直同步刷新. 编辑~/.drirc <driconf> <device screen=" driver=" ...

  3. 学习PHP注意事项

    1 多阅读手册和源代码 没什么比阅读手册更值得强调的事了–仅仅通过阅读手册你就可以学习到很多东西,特别是很多有关于字符串和数组的函数.就在这些函数里面包括许多有用的功能,如果你仔细阅读手册,你会经常发 ...

  4. hadoop之深入浅出

    分布式文件系统与HDFS lHDFS体系结构与基本概念*** l数据量越来越多,在一个操作系统管辖的范围存不下了,那么就分配到更多的操作系统管理的磁盘中,但是不方便管理和维护,因此迫切需要一种系统来管 ...

  5. HashSet底层存储元素的源码分析

    此类实现 Set 接口,由哈希表(实际上是一个 HashMap 实例)支持.它不保证 set 的迭代顺序:特别是它不保证该顺序恒久不变.此类允许使用 null 元素. HashSet<Strin ...

  6. [USACO17DEC] Barn Painting

    题目描述 Farmer John has a large farm with NN barns (1 \le N \le 10^51≤N≤105 ), some of which are alread ...

  7. Ubuntu 16.04使用timedatectl进行管理时间(UTC/CST)(服务器/桌面)

    说明:16.04开始,systemd接管了系统之后就不再使用/etc/default/rcS和ntpdate.dpkg-reconfigure tzdata进行时间的管理,所以在这些地方设置是无效的, ...

  8. QQ协议

    http://www.cnblogs.com/sufei/archive/2012/12/13/2816737.html http://www.360doc.com/content/12/0822/1 ...

  9. HashMap在高并发下引起的死循环

    HashMap事实上并非线程安全的,在高并发的情况下,是非常可能发生死循环的,由此造成CPU 100%,这是非常可怕的.所以在多线程的情况下,用HashMap是非常不妥当的行为,应採用线程安全类Con ...

  10. JAVA常见算法题(十一)

    package com.xiaowu.demo; /** * 有1.2.3.4个数字,能组成多少个互不相同且无重复数字的三位数?都是多少? * * * @author WQ * */ public c ...