Android中使用http协议访问网络
HTTP协议的工作原理:客户端向服务器端发送http请求,服务器端收到请求后返回一下数据给客户端,客户端接受消息并进行解析。
在Android中发送http请求的方式有两种,第一种是通过HttpURLConnection的方式,第二种是通过HttpClient的方式。
通过HttpURLConnection的方式发送http请求
通常分为以下5个步骤:
1.获取HttpURLConnection实例对象。先new一个URL实例,然后调用该对象的openConnection()方法。
2.设置http请求使用的方法(get和post方法,get方法是从服务器获取数据,post是向服务器发送数据)。
3.自由设定参数,如连接超时、读取超时等。
4.调用getInputStream()方法获取服务返回的信息。
5.调用disconnect()方法将http连接关闭。
现在是简单实现的代码:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
> <Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/send_request"
android:text="send request" /> <ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"> <TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/response"
android:hint="nihao,zhelixianshinierong"
/>
</ScrollView> </LinearLayout>
activity_main.xml
这是Java代码
package com.example.yqt.networktest; import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
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; Button sentRequestBtn;
TextView responseText; Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) { switch (msg.what){
case SHOW_RESPONSE: String response = (String) msg.obj;
responseText.setText(response);
}
//super.handleMessage(msg); }
}; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); sentRequestBtn = (Button)findViewById(R.id.send_request);
responseText = (TextView)findViewById(R.id.response); sentRequestBtn.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 reader = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder(); String line;
while ((line = reader.readLine()) !=null){
response.append(line);
} Message message = new Message();
message.what = SHOW_RESPONSE;
message.obj = response.toString();
handler.sendMessage(message); }catch (Exception e){
e.printStackTrace();
}finally {
if(connection != null){
connection.disconnect();
}
}
}
}).start();
} }
mainactivity.java
通过HttpClient的方式发送http请求
HttpClient是Apache提供的http网络访问的接口。
1.创建一个DefaultHttpClient的实例
2.创建一个HttpGet对象,并传入目标网络地址,调用execute()方法。
3.获取返回码,判断连接是否成功。若成功,还可提取相应数据。
Android中使用http协议访问网络的更多相关文章
- Android 使用 HTTP 协议访问网络
正在看<第一行代码>,记录一下使用 HTTP 协议访问网络的内容吧! 在Android发送Http请求有两种方式,HttpURLConnection和HttpClient. 1.使用Htt ...
- Android 中多点触摸协议
http://blog.csdn.net/zuosifengli/article/details/7398661 Android 中多点触摸协议: 参考: http://www.kernel.org/ ...
- 使用HTTP协议访问网络(Android)
在做项目的过程中需要连接服务器访问数据,还没有接触过Android网络编程方面,参考了<Android第一行代码>,在做的过程中遇到了很多的问题,这里就此记录一下. 先给出访问网络的代码: ...
- Android使用Http协议访问网络——HttpConnection
套路篇 使用HttpConnection访问网络一般有如下的套路: 1.获取到HttpConnection的实例,new出一个URL对象,并传入目标的网址,然后调用一下openConnection() ...
- Android中的安全与访问权限控制
Android是一个多进程系统,在这个系统中,应用程序(或者系统的部分)会在自己的进程中运行.系统和应用之间的安全性是通过Linux的facilities(工具,功能)在进程级别来强制实现的,比如会给 ...
- Android使用HTTP协议访问网络——HttpClient
套路篇 1.HttpClient是一个接口,因此无法创建它的实例,通常情况下都会创建一个DefaultHttpClient的实例 HttpClient httpClient=new DefaultHt ...
- 第一行代码 10.2使用HTTP协议访问网络 HttpURLConnection代码中的问题
实现HttpURLConnection代码的时候,遇到了问题. 怎样点击途中Send Request按钮,没有任何改变. 最后将MainActivity中的一段代码URL url = new URL( ...
- android黑科技系列——Wireshark和Fiddler分析Android中的TLS协议包数据(附带案例样本)
一.前言 在之前一篇文章已经介绍了一款网络访问软件的破解教程,当时采用的突破口是应用程序本身的一个漏洞,就是没有关闭日志信息,我们通过抓取日志获取到关键信息来找到突破口进行破解的.那篇文章也说到了,如 ...
- 【转】Wireshark和Fiddler分析Android中的TLS协议包数据(附带案例样本)
本文转自:http://www.wjdiankong.cn/wireshark%E5%92%8Cfiddler%E5%88%86%E6%9E%90android%E4%B8%AD%E7%9A%84tl ...
随机推荐
- LightOJ 1336 Sigma Function 算数基本定理
题目大意:f(n)为n的因子和,给出 n 求 1~n 中f(n)为偶数的个数. 题目思路:算数基本定理: n=p1^e1*p2^e1 …… pn^en (p为素数): f(n)=(1+p1+p1^2+ ...
- UVA - 10635 最长公共子序列
input n,p,q 2<=n<=250 1<=p,q<=n*n 1 a1 a2 a3 ... ap 1<ai<n*n,ai!=aj 1 b1 b2 b3 ... ...
- Hadoop学习笔记—5.自定义类型处理手机上网日志
转载自http://www.cnblogs.com/edisonchou/p/4288737.html Hadoop学习笔记—5.自定义类型处理手机上网日志 一.测试数据:手机上网日志 1.1 关于这 ...
- cocos2d-x3.x Vector
auto sp0 = Sprite::create(); sp0->setTag(); auto sp1 = Sprite::create(); sp1->setTag(); //这里使用 ...
- HDU - 1702 ACboy needs your help again!(栈和队列)
Description ACboy was kidnapped!! he miss his mother very much and is very scare now.You can't image ...
- Kth order statistcs
Selection: selection is a trivial problem if the input numbers are sorted. If we use a sorting algor ...
- 【转】PHP里的basename函数不支持中文名的解决
今天用到basename 函数获取文件名称时,发现如果是中文的文件名返回只有后缀的空文件名(如:.pdf) string basename ( string path [, string suf ...
- Apache 实现ProxyPass转发URL到Tomcat并实现http自动转https【转载】
转自 Apache 实现ProxyPass转发URL到Tomcat并实现http自动转https - OPEN 开发经验库http://www.open-open.com/lib/view/open1 ...
- asp.net MVC 3多语言方案--再次写, 配源码
之前写了一篇asp.net MVC多语言方案,那次其实是为American Express银行开发的.有许多都是刚开始接触,对其也不太熟悉.现在再回过头去看,自己做一个小网站,完全用asp.net m ...
- How to spend you day ?
如果这是你生命中的最后的一天,你该如何去过好它呢? 不要浪费你生命中的每一分,每一秒!!!