Android使用Http协议访问网络——HttpConnection
套路篇
使用HttpConnection访问网络一般有如下的套路:
1.获取到HttpConnection的实例,new出一个URL对象,并传入目标的网址,然后调用一下openConnection()方法。
HttpURLConnection connection=null;
URL url=new URL("http://www.baidu.com");
connection=(HttpURLConnection)url.openConnection();
2.得到了HttpConnection的实例后,设置请求所用的方法(GET:从服务器获取数据,POST:提交数据给服务器)
connection.setRequestMethod("GET");或
connection.setRequestMethod("POST");
3.自由定制的环节(设置连接超时,读取的毫秒数,以及服务器希望得到的消息头等)
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
4.利用getInputStream()方法获取服务器的返回的输入流,然后读取
InputStream in=connection.getInputStream();
//下面对获取到的输入流进行读取
BufferedReader bufr=new BufferedReader(new InputStreamReader(in));
StringBuilder response=new StringBuilder();
String line=null;
while((line=bufr.readLine())!=null){
response.append(line);
}
5.调用disconnect()方法将HTTP连接关闭掉
if(connection!=null){
connection.disconnect();
}
实战篇
新建一个Android工程
1.activity_main.xml(里面有一个Button和一个TextView)
<?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/send_request"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send Request" /> <ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"> <TextView
android:id="@+id/response_text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</ScrollView>
</LinearLayout>
2.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 java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL; public class MainActivity extends AppCompatActivity implements View.OnClickListener { public static final int SHOW_RESPONSE=0;//用于更新操作
private Button sendRequest;
private TextView responseText; //用于处理和发送消息的Hander
private Handler handler=new Handler(){
public void handleMessage(Message msg){
//如果返现msg.what=SHOW_RESPONSE,则进行制定操作,如想进行其他操作,则在子线程里将SHOW_RESPONSE改变
switch (msg.what){
case SHOW_RESPONSE:
String response=(String)msg.obj;
//进行UI操作,将结果显示到界面上
responseText.setText(response);
}
}
}; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendRequest=(Button)findViewById(R.id.send_request);
responseText=(TextView)findViewById(R.id.response_text);
sendRequest.setOnClickListener(this);
} @Override
public void onClick(View v) {
if(v.getId()==R.id.send_request){
sendRequestWithHttpURLConnection();
}
} private void sendRequestWithHttpURLConnection(){
//开启线程来发起网络请求
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection=null;
try{
URL url=new URL("http://www.baidu.com");
connection=(HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000); InputStream in=connection.getInputStream();
//下面对获取到的输入流进行读取
BufferedReader bufr=new BufferedReader(new InputStreamReader(in));
StringBuilder response=new StringBuilder();
String line=null;
while((line=bufr.readLine())!=null){
response.append(line);
} Message message=new Message();
message.what=SHOW_RESPONSE;
//将服务器返回的数据存放到Message中
message.obj=response.toString();
handler.sendMessage(message);
}catch(Exception e){
e.printStackTrace();
}finally {
if(connection!=null){
connection.disconnect();
}
}
}
}).start();
}
}
3.AndroidManifest.xml中注册权限
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
好,这个简单的例子就弄完了,接下来就看看效果吧。
这样我们就可以看到服务器返回给我们的数据了。
Android使用Http协议访问网络——HttpConnection的更多相关文章
- Android 使用 HTTP 协议访问网络
正在看<第一行代码>,记录一下使用 HTTP 协议访问网络的内容吧! 在Android发送Http请求有两种方式,HttpURLConnection和HttpClient. 1.使用Htt ...
- Android使用HTTP协议访问网络——HttpClient
套路篇 1.HttpClient是一个接口,因此无法创建它的实例,通常情况下都会创建一个DefaultHttpClient的实例 HttpClient httpClient=new DefaultHt ...
- 使用HTTP协议访问网络(Android)
在做项目的过程中需要连接服务器访问数据,还没有接触过Android网络编程方面,参考了<Android第一行代码>,在做的过程中遇到了很多的问题,这里就此记录一下. 先给出访问网络的代码: ...
- Android主线程不能访问网络异常解决办法
从两个方面说下这个问题: 1. 不让访问网络的原因 2. 解决该问题的办法 不让访问网络的原因: 由于对于网络状况的不可预见性,很有可能在网络访问的时候造成阻塞,那么这样一来我们的主线程UI线程 就会 ...
- Android中使用http协议访问网络
HTTP协议的工作原理:客户端向服务器端发送http请求,服务器端收到请求后返回一下数据给客户端,客户端接受消息并进行解析. 在Android中发送http请求的方式有两种,第一种是通过HttpURL ...
- 第一行代码 10.2使用HTTP协议访问网络 HttpURLConnection代码中的问题
实现HttpURLConnection代码的时候,遇到了问题. 怎样点击途中Send Request按钮,没有任何改变. 最后将MainActivity中的一段代码URL url = new URL( ...
- 使用HTTP协议访问网络
在Android上发送http请求有2种方式,分别由两个类完成,HttpURLConnection和HttpClient. 一.使用HttpURLConnection方式 1.1 建立连接的基本步骤 ...
- Android Studio模拟器无法访问网络
Android Studio3.5 模拟器无法访问网络的原因?
- HttpConnection方式访问网络
参考疯狂android讲义,重点在于学习1.HttpConnection访问网络2.多线程下载文件的处理 主activity: package com.example.multithreaddownl ...
随机推荐
- Java面向对象—抽象类和接口
本文引用海子的一篇文章:http://www.cnblogs.com/dolphin0520/p/3811437.html 一.抽象类 在了解抽象类之前,先来了解一下抽象方法.抽象方法是一种特殊的方法 ...
- PL/SQL编程—变量
SQL> declare c_tax_rate ,):=0.03; v_name ); v_passwd ); v_sale ,); v_tax_sale ,); begin select na ...
- MySQL Binlog解析(1)
一.Binlog File Binlog files start with a Binlog File Header followed by a series of Binlog Event Binl ...
- Zabbix 自定义Key
系统:Linux Centos 7.4 x64.Windos 2008 x64 服务:Zabbix 3.0.16 说明1:自定义Key 主要通过自定义 脚本 或者 命令 来实现自定义监控类型,需要在a ...
- apache性能测试工具ab
性能测试工具目前最常见的有以下几种:ab.http_load.webbench.siege ab是apache自带的压力测试工具.ab非常实用,它不仅可以对apache服务器进行网站访问压力测试,也可 ...
- git代码提交与克隆
在工作中,越来越多的人会使用git来管理代码.下面简单的介绍一下git在工作中的使用流程 1.给你一个git地址,将代码拉下来基本操作流程如下: 1.1 git clone "项目地址&qu ...
- DCU IP Prefether
DCU IP Prefether 数据高速缓存单元预取I P 设置.如果设置为E n a b l e d,会预取I P 地址以改善网络连接和系统性能,所以建议选择E n a b l ed.选项:E n ...
- mkfs.ext4 磁盘分区
在linux上格式化一个磁盘分区时,出现如下错误 root@d:~# mkfs.ext4 /dev/sdb1 mke2fs 1.41.12 (11-May-2015) mkfs.ext4: inode ...
- JNIjw05
ZC: 这个代码,没有真正的运行测试 1.VC6(CPP)的DLL代码: #include<stdio.h> #include "jniZ_JNIjw05.h" #in ...
- selenium学习笔记(webdriver下载配置)
selenium安装后默认安装firefox可以直接使用,当然可以通过其它浏览器 博主这里整理了:chrome . IE 首先是下载地址 http://docs.seleniumhq.org/down ...