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 ...
随机推荐
- PHPcms 调用命令的基本格式:
PHPcms 调用命令的基本格式: 开始:{pc:content action="模块操作名" catid="调用栏目ID" num="数据调用数量& ...
- 广州亿能自动化测试沙龙 - 自动化测试管理平台设计 [ 沙龙PPT免费下载 ]
广州亿能自动化测试沙龙 - 自动化测试管理平台设计 [ 沙龙PPT免费下载 ] http://automationqa.com/forum.php?mod=viewthread&tid=244 ...
- 部署 LAMP (CentOS 7.2),摘自阿里云,方便查看使用
原文地址:https://help.aliyun.com/document_detail/50774.html?spm=5176.product25365.6.728.C9s3V8 简介 LAMP指L ...
- SpringBoot2.0+ElasticSearch网盘搜索实现
1.ES是如何实现分布式高并发全文检索 2.简单介绍ES分片Shards分片技术 3.为什么ES主分片对应的备分片不在同一台节点存放 4.索引的主分片定义好后为什么不能做修改 5.ES如何实现高可用容 ...
- TNS-12541: TNS:no listener , TNS-12542: TNS:address already in use
查看数据库监听状态不对$ lsnrctl status LSNRCTL for IBM/AIX RISC System/6000: Version 10.2.0.5.0 - Production on ...
- NUnit单元测试笔记
vs2010 和 NUnit 问题处理. . 在 <configuration> 下 加 ... <startup> <requiredRuntime version=& ...
- virtualbox ubuntu下ssh连接
一.首先Ubuntu中安装ssh服务器 Ubuntu 下安装 OpenSSH Server 是无比轻松的一件事情,需要的命令只有一条: sudo apt-get install openssh-ser ...
- java.util.logging.Logger_01
1.参考网址 1.1.java.util.logging.Logger使用详解 http://lavasoft.blog.51cto.com/62575/184492 1.2.Java内置Logger ...
- koa2使用&&中间件&&angular2的koa托管
文章导航 1,koa2使用: 2,写中间件: 3,koa2路由配置angular2; 一.先上代码,一篇,看完koa2中大多基础方法: const Koa=require('koa'); const ...
- spring3: AOP 之 通知参数
前边章节已经介绍了声明通知,但如果想获取被被通知方法参数并传递给通知方法,该如何实现呢?接下来我们将介绍两种获取通知参数的方式. 使用JoinPoint获取:Spring AOP提供使用org.asp ...