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 ...
随机推荐
- Elasticsearch Server,2nd Edition pdf 翻译 中文
很偶然的机会,就需要接触到搜索,入门就是google trend已然超过solr的ES.在入门的时候找书的时候发现没有中文版的.于是自己开始翻译Elasticsearch Server,2nd Edi ...
- mac下搭建基于vue-cli 3.0的Element UI 项目
1.安装yarn管理工具(包含node.js); 2.安装全局vue-cli全家桶: yarn global add @vue/cli 3.创建.测试一个vue-cli项目: vue create a ...
- 自学Java测试代码一数据类型、数组使用
2017-08-22 21:23:37. writer:pprp package test; public class helloWorld { int maxn = 123; //常量,需要定义一个 ...
- Mac Homebrew安装php56 到phpstorm过程问题汇总
Mac自带版本是php5.5,本来是用homebrew安装xdebug 命令:brew install php55-xdebug 但是安装之后使用phpstorm还是有问题.php -v 并没有显示有 ...
- 解决 ORA-28001: the password has expired 问题
1.首先需要使用dba登录. 2.运行SQLPlus命令行工具, 输入: connect as sysdba; 3.输入dba的用户名和密码后进行 4.ALTER USER 用户名 IDENTIFIE ...
- Educational Codeforces Round 13 A、B、C、D
A. Johny Likes Numbers time limit per test 0.5 seconds memory limit per test 256 megabytes input sta ...
- 微信小程序:scroll-view的bug
flex:1并不能使scroll-view的高度固定,需要添加高度height:1rpx(数值大于0)就行
- 设置table的td宽度,不随文字变宽
页面中table宽度设置width="600px"之后,宽度仍然不是固定的,文字太长后不换行,把table都撑变形了. 解决办法: table 设置 宽度,绝对宽度和相对都可以 t ...
- C# 终于写完了简单的ORM
实现单表 增 .删. 改 .查 使用接口定义表实体数据.实体对象动态创建,使用 Email 进行数据读取. 存储过程调用示例
- ML之多元线性回归
转自:http://www.cnblogs.com/zgw21cn/archive/2009/01/07/1361287.html 1.多元线性回归模型 假定被解释变量与多个解释变量之间具有线性关系, ...