Android使用HTTP协议访问网络——HttpClient
套路篇
1.HttpClient是一个接口,因此无法创建它的实例,通常情况下都会创建一个DefaultHttpClient的实例
HttpClient httpClient=new DefaultHttpClient();
2.如果想要发起一条GET请求,就创建一个HttpGet对象,并传入目标网络的对象,然后调用HtttpClient中的excute()方法:
HttpGet httpGet=new HttpGet("http://www.baidu.com");
HttpResponse httpResponse=httpClient.execute(httpGet);
如果想发起一条POST请求会比GET复杂一点,首先创建一个HttpPost对象,并传入目标网址
HttpPost httpPost=new HttpPost("http/:www.baidu.com");
然后通过NameValuePair集合来存放待提交的数据,并将这个参数传入到一个UrlEncodedFormEntity中,然后调用HttpPost的setEntity()方法将构建好的UrlEncodedFormEntity传入
List<NameValuePair> params=new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("username","admin")); params.add(new BasicNameValuepair("password","123456")); UrlEncodeFormEntity entity=new UrlEncodeFormEntity(params,"utf-8"); httpPost.setEntity(entity);
接下来就和GET方法一样啦,httpClient.execute(httpPost);
3.执行完execute()方法后会返回一个HttpResponse对象,服务器返回的数据都在里面,通常我们会先取出服务器返回的状态码,如果等于200,则说明请求响应成功
if(httpResponse.getStatusLine().getStatueCode()==200){ //请求和响应都成功了 }
4.读取服务器返回的具体内容,可以调用getEntity()访问获取到一个HttpEntity实例,然后调用EntityUtils.toString()这个静态类将HttpEntity转换成字符串
HttpEntity entity=httpResponse.getEntity();
String response=EntityUtils.toString(entity);
如果返回的数据带有中文,转换的时候需要将字符集指定为utf-8
String response=EntityUtils.toString(entity,"utf-8");
实战篇
MainActivity
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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; public class MainActivity extends AppCompatActivity implements View.OnClickListener{ public static final int SHOW_RESPONSE=0;//用于更新操作
private Button sendRequest_Button;
private TextView responseText; //用于处理和发送消息的Handler
private Handler handler=new Handler(){
public void handleMessage(Message msg){
switch (msg.what){
case SHOW_RESPONSE:
String response=(String)msg.obj;
responseText.setText(response);
}
}
}; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendRequest_Button=(Button)findViewById(R.id.sendrequest);
responseText=(TextView)findViewById(R.id.response_text);
sendRequest_Button.setOnClickListener(this);
} @Override
public void onClick(View v) {
if(v.getId()==R.id.sendrequest){
sendRequestWithHttpClient();
}
} public void sendRequestWithHttpClient(){
new Thread(new Runnable() {
@Override
public void run() {
try{
HttpClient httpClient=new DefaultHttpClient();
HttpGet httpGet=new HttpGet("http://www.baidu.com");
HttpResponse httpResponse=httpClient.execute(httpGet);
if(httpResponse.getStatusLine().getStatusCode()==200){
//请求和响应都成功了
HttpEntity entity=httpResponse.getEntity();
String response= EntityUtils.toString(entity, "utf-8"); Message message=new Message();
message.what=SHOW_RESPONSE;
//将服务器返回的结果保存到Message中
message.obj=response.toString();
handler.sendMessage(message); } }catch(Exception e){ }finally { } }
}).start(); } }
AndroidManifest
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"> <Button
android:id="@+id/sendrequest"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send Request"/> <ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"> <TextView
android:id="@+id/response_text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</ScrollView>
</LinearLayout>
Android使用HTTP协议访问网络——HttpClient的更多相关文章
- Android 使用 HTTP 协议访问网络
正在看<第一行代码>,记录一下使用 HTTP 协议访问网络的内容吧! 在Android发送Http请求有两种方式,HttpURLConnection和HttpClient. 1.使用Htt ...
- Android使用Http协议访问网络——HttpConnection
套路篇 使用HttpConnection访问网络一般有如下的套路: 1.获取到HttpConnection的实例,new出一个URL对象,并传入目标的网址,然后调用一下openConnection() ...
- 使用HTTP协议访问网络(Android)
在做项目的过程中需要连接服务器访问数据,还没有接触过Android网络编程方面,参考了<Android第一行代码>,在做的过程中遇到了很多的问题,这里就此记录一下. 先给出访问网络的代码: ...
- Android主线程不能访问网络异常解决办法
从两个方面说下这个问题: 1. 不让访问网络的原因 2. 解决该问题的办法 不让访问网络的原因: 由于对于网络状况的不可预见性,很有可能在网络访问的时候造成阻塞,那么这样一来我们的主线程UI线程 就会 ...
- Android中使用http协议访问网络
HTTP协议的工作原理:客户端向服务器端发送http请求,服务器端收到请求后返回一下数据给客户端,客户端接受消息并进行解析. 在Android中发送http请求的方式有两种,第一种是通过HttpURL ...
- 使用HTTP协议访问网络
在Android上发送http请求有2种方式,分别由两个类完成,HttpURLConnection和HttpClient. 一.使用HttpURLConnection方式 1.1 建立连接的基本步骤 ...
- 第一行代码 10.2使用HTTP协议访问网络 HttpURLConnection代码中的问题
实现HttpURLConnection代码的时候,遇到了问题. 怎样点击途中Send Request按钮,没有任何改变. 最后将MainActivity中的一段代码URL url = new URL( ...
- Android Studio模拟器无法访问网络
Android Studio3.5 模拟器无法访问网络的原因?
- android 使用httpclient访问网络
在主活动类中,调用一个线程访问网络(android4.0以上耗时的操作不能放在主线程中): //声明两个Button对象,与一个TextView对象private TextView mTe ...
随机推荐
- jQuery的$.each()遍历checkbox
$("input[type='checkbox']").each(function(){ var value = $(this).val(); //获得值 $(this).attr ...
- .net 修改AD域中的密码
1.通过vs 2013 新建一个web站点(不是空项目),这个会带一下模板, 2.然后新建一个页面UpdatePassWord.aspx aspx页面内容: <%@ Page Title=&qu ...
- zpar使用方法之Chinese Word Segmentation
第一步在这里: http://people.sutd.edu.sg/~yue_zhang/doc/doc/qs.html 你可以找到这句话, 所以在命令行中分别敲入 make zpar make zp ...
- 理解多线程管理类 CWorkQueue
有些人会觉得多线程无非是,有多少任务就启动多少线程,CreadThread,执行完了自己结束就释放资源了,其实不然.多线程是需要管理的,线程的启动.执行.等待和结束都需要管理,线程间如何通信,如何共享 ...
- 无法启动此程序,因为计算机丢失MSVCP120.dll
这种错误是由于未安装** vcredist **引起的(而且版本是 2013版):https://www.microsoft.com/zh-CN/download/details.aspx?id=40 ...
- switchhosts使用技巧
https://jingyan.baidu.com/article/1974b289a3cfd1f4b0f7744d.html
- ECMAScript6教程目录
ECMAScript 6 简介 let 和 const 命令 数组的解构赋值 字符串的扩展 正则的扩展 数值的扩展 函数的扩展 数组的扩展 对象的扩展 Symbol Set 和 Map 数据结构 Pr ...
- 实现Promise的first等各种变体
本篇文章主要是想通过ES6中Promise提供的几个方法,来实现诸如first.last.none.any等各种变体方法! 在标准的ES6规范中,提供了Promise.all和Promise.race ...
- 英语每日阅读---5、VOA慢速英语(翻译+字幕+讲解):美国人口普查局表示美国人受教育程度提升
英语每日阅读---5.VOA慢速英语(翻译+字幕+讲解):美国人口普查局表示美国人受教育程度提升 一.总结 一句话总结: a.Thirty-four percent - college degree: ...
- Python之路day12 web 前端(HTML+ css)
HTML文档 文档树: Doctype Doctype告诉浏览器使用什么样的html或xhtml规范来解析html文档 有和无的区别 BackCompat:标准兼容模式未开启(或叫怪异模式[Quirk ...