套路篇

使用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的更多相关文章

  1. Android 使用 HTTP 协议访问网络

    正在看<第一行代码>,记录一下使用 HTTP 协议访问网络的内容吧! 在Android发送Http请求有两种方式,HttpURLConnection和HttpClient. 1.使用Htt ...

  2. Android使用HTTP协议访问网络——HttpClient

    套路篇 1.HttpClient是一个接口,因此无法创建它的实例,通常情况下都会创建一个DefaultHttpClient的实例 HttpClient httpClient=new DefaultHt ...

  3. 使用HTTP协议访问网络(Android)

    在做项目的过程中需要连接服务器访问数据,还没有接触过Android网络编程方面,参考了<Android第一行代码>,在做的过程中遇到了很多的问题,这里就此记录一下. 先给出访问网络的代码: ...

  4. Android主线程不能访问网络异常解决办法

    从两个方面说下这个问题: 1. 不让访问网络的原因 2. 解决该问题的办法 不让访问网络的原因: 由于对于网络状况的不可预见性,很有可能在网络访问的时候造成阻塞,那么这样一来我们的主线程UI线程 就会 ...

  5. Android中使用http协议访问网络

    HTTP协议的工作原理:客户端向服务器端发送http请求,服务器端收到请求后返回一下数据给客户端,客户端接受消息并进行解析. 在Android中发送http请求的方式有两种,第一种是通过HttpURL ...

  6. 第一行代码 10.2使用HTTP协议访问网络 HttpURLConnection代码中的问题

    实现HttpURLConnection代码的时候,遇到了问题. 怎样点击途中Send Request按钮,没有任何改变. 最后将MainActivity中的一段代码URL url = new URL( ...

  7. 使用HTTP协议访问网络

    在Android上发送http请求有2种方式,分别由两个类完成,HttpURLConnection和HttpClient. 一.使用HttpURLConnection方式 1.1 建立连接的基本步骤 ...

  8. Android Studio模拟器无法访问网络

    Android Studio3.5 模拟器无法访问网络的原因?

  9. HttpConnection方式访问网络

    参考疯狂android讲义,重点在于学习1.HttpConnection访问网络2.多线程下载文件的处理 主activity: package com.example.multithreaddownl ...

随机推荐

  1. Python框架之Tornado(请求)

    概述 本篇就来详细介绍tornado服务器(socket服务端)是如何接收用户请求数据以及如果根据用户请求的URL处理并返回数据,也就是上图的3系列所有步骤,如上图[start]是一个死循环,其中利用 ...

  2. linux:查看磁盘硬件信息hdparm,smartctl

    smartctl 命令 这个一个用于控制和监控支持smart技术的硬盘的命令.通常配合 -a 选项我们可以查看到比较详尽的硬盘信息(比如序列号.硬盘容量.已运行时间.硬盘健康状况等).用法如下: sm ...

  3. jQuery获取URL的GET参数值

    // jQuery url get parameters function [获取URL的GET参数值] // <code> // var GET = $.urlGet(); //获取UR ...

  4. 一年java程序员的感悟

    前沿 在小公司干了差不多一年,刚进来与一个中级程序员做交接,过了大概一个月,那个中级程序员走了,从此,走上了"泥泞"的道路(独立开发),熟悉了公司的项目和业务用了一个月左右,公司当 ...

  5. pt-osc原理

    pt-osc原理 1.检查设置环境 测试db是否可连通,并且验证database是否存在 SET SESSION innodb_lock_wait_timeout=1 //InnoDB事务等待行锁的超 ...

  6. SpringBoot中使用hikariCP

    本篇文章主要实现SpringBoot中使用hikariCP: 一 .使用工具 1. JDK1.8 2. springToolSuit(STS) 3. maven 二.创建项目 1.首先创建一个Spri ...

  7. iOS 开发 申请定位

    在iOS8以后,苹果已经强制开发者在请求定位服务时获得用户的授权,此外iOS状态栏中还有指示图标,提示用户当前应用是否正在使用定位服务.另外在iOS8以后,苹果进一步改善了定位服务,让开发者请求定位服 ...

  8. Spring_HelloWorld

    目录: 各个类文件: pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="h ...

  9. java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[]]

    1.问题描述: 对于创建的springboot项目,通过启动类启动,访问没问题,但打成war部署到tomcat上启动报错,如下: 严重: ContainerBase.addChild: start: ...

  10. springboot处理session生命周期

    在使用springboot开发过程中发现用户登陆后60s后session就自动失效了,需要重新登陆,明明 application.yml  文件里已经配置了 server.session.timeou ...