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 ...
随机推荐
- MySQL修改max_allowed_packet
因mysql从库报错Last_IO_Error: Got a packet bigger than 'max_allowed_packet' bytes mysql> show slave st ...
- 微信JS-SDK接口,分享到朋友圈”按钮点击状态及自定义分享内容接口
jssdk.php 接口文件class JSSDK { private $appId; private $appSecret; public function __construct($appId, ...
- 一致性hash演示
看到点关于一致性hash的说明,觉得挺有意思,就想体验一下. 上代码看看,体会一下在一致性hash环境下的cache和获取. 因为是小代码演示,没有很细致,包括hash函数就是用取余操作,但活生生的显 ...
- ubuntu 18. use gnome-tweaks
<<install gnome-tweaks sudo apt-get install gnome-tweaks <<run gnome-tweaks >>pres ...
- sprites.png雪碧图
长时间不用把精灵图怎么用给忘了... 一.PC端 给所用到精灵图的元素设置background:url(sprites.png路径); background-position: -x -y; 其中: ...
- 如何停止你的Streaming Application
Spark 1.3及其前的版本 你的一个 spark streaming application 已经好好运行了一段时间了,这个时候你因为某种原因要停止它.你应该怎么做?直接暴力 kill 该 app ...
- mongodb安装、运行
1.下载安装: 切换到:/usr/local/ mkdir -p mongodb groupadd -g 800 mongodb useradd -u 801 -g mongodb mongodb c ...
- spring mvc:输出json,输出多个json
spring mvc:输出xml/输出json 用到的注解@ResponseBody @ResponseBody用来输出json/xml等格式数据(非html) controller输出用到的类 or ...
- Runtime.getRuntime.exec();
杀死Chrome浏览器进程 private static void closeAllChrome() throws IOException{ Runtime.getRuntime().exec(&qu ...
- bzoj1001平面图最小割转对偶图最短路
https://www.lydsy.com/JudgeOnline/problem.php?id=1001 很明显的求对偶图的最短路即可(由于特判写错了一直wa = = ) //#pragma com ...