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 ...
随机推荐
- Scrapy 分布式数据采集方案
运行环境 CentOS7. + Python2. + Scrapy1. + MongoDB3. + BeautifulSoup4. 编程工具 PyCharm + Robomongo + Xshell ...
- pt-table-sync修复mysql主从不一致的数据
pt-table-sync简介 顾名思义,它用来修复多个实例之间数据的不一致.它可以让主从的数据修复到最终一致,也可以使通过应用双写或多写的多个不相关的数据库实例修复到一致.同时它还内部集成了pt-t ...
- LeetCode——Range Sum Query - Immutable
Question Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), ...
- spark(四)yarn上的运行模式
架构图 yarn-cluster yarn-client 区别 Yarn-cluster spark的driver运行在applicationMaster内,启动流程为: 这张图可能比较直观 Yarn ...
- webservice的cxf和spring整合发布
1.新建一个web项目 2.导入cxf相应的jar包,并部署到项目中 3.服务接口 package com.xiaostudy; /** * @desc 服务器接口 * @author xiaostu ...
- ACM输入函数测试 - scanf cin 优化的输入
2017-08-27 10:26:19 writer:pprp 进行测试如下四种输入方式: 1.scanf 2.cin 3.用了ios::sync_with_stdio(false);的cin 4.自 ...
- Dll Hijacker
#coding=utf-8 # # Dll Hijacker # # platform: Python 2.x @ Windows # # author:Coca1ne import os,sys,t ...
- C++11 auto类型说明符的使用
编程的时候常常需要把表达式的值赋给变量,这就要求在声明变量的时候清楚地知道表达式的类型.然而做到这一点很难,有时候根本做不到.为了解决这个问题.C++11新标准引入了auto类型说明符,用它就 能让编 ...
- Angular for TypeScript 语法快速指南 (基于2.0.0版本)
引导 import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; platformBrowserDynami ...
- 玲珑oj 1121 思维
1121 - Reverse the lights Time Limit:2s Memory Limit:256MByte Submissions:376Solved:111 DESCRIPTION ...