正在看《第一行代码》,记录一下使用 HTTP 协议访问网络的内容吧!

  在Android发送Http请求有两种方式,HttpURLConnection和HttpClient。

   1.使用HttpURLConnection

   首先要获取到HttpURLConnection的实例,只需要new出一个URL对象,并传入目标网络地址,然后调用一下openConnect()方法。  

 URL url = new URL("http://www.baidu.com"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 

    得到HttpURLConnection实例之后,设置HTTP请求使用的方法(POST和GET),GET是希望从服务器得到数据,而POST就是希望发生数据到服务器了。

   

connection.setRequestMethod("GET"); 

      这里可以对connection做一些设置,读取超时毫秒数,连接超时等等。

 

connection.setConnectTimeout(8000); connection.setReadTimeout(8000); 

    接着调用getInputStream()方法就可以获得服务器返回的输入流了,这时就可以对输入流进行读取。最后需要关闭connection。

InputStream in = connection.getInputStream();
connection.disconnect();

    具体代码(来自书本) 

<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" android:layout_width="match_parent" android:layout_height="wrap_content" /> </ScrollView>
</LinearLayout>
public class MainActivity extends Activity implements OnClickListener {
public static final int SHOW_RESPONSE = 0;
private Button sendRequest;
第 10章 看看精彩的世界,使用网络技术
399
private TextView responseText;
private Handler handler = new Handler() {
public void handleMessage(Message msg) { 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();
第一行代码——Android
400
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中 message.obj = response.toString(); handler.sendMessage(message); } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } } }).start(); }
}

     最后别忘了添加网络权限。

 <uses-permission android:name="android.permission.INTERNET" /> 

    另外如果想向服务器发送数据,只需要将 HTTP请求 的方法改成 POST,并在获取输入流之前把要提交的数据写出即可,注意每条数据都要以键 值对的形式存在,数据与数据之间用&符号隔开,比如说我们想要向服务器提交用户名和密 码,就可以这样写:
connection.setRequestMethod("POST");

DataOutputStream out = new DataOutputStream(connection.getOutputStream());

out.writeBytes("username=admin&password=123456");

  

Android 使用 HTTP 协议访问网络的更多相关文章

  1. Android使用Http协议访问网络——HttpConnection

    套路篇 使用HttpConnection访问网络一般有如下的套路: 1.获取到HttpConnection的实例,new出一个URL对象,并传入目标的网址,然后调用一下openConnection() ...

  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. android 使用httpclient访问网络

    在主活动类中,调用一个线程访问网络(android4.0以上耗时的操作不能放在主线程中):       //声明两个Button对象,与一个TextView对象private TextView mTe ...

随机推荐

  1. Javascript中的数据类型之旅

    虽然Javascript是弱类型语言,但是,它也有自己的几种数据类型,分别是:Number.String.Boolean.Object.Udefined.Null.其中,Object属于复杂数据类型, ...

  2. POJ1469COURSES(二分图匹配)

    裸的二分图匹配 题目poj.org/problem?id=1469 不解释:

  3. C#图解教程读书笔记(第15章 委托)

    委托是C#的一个很重要的知识点. 1.什么是委托 委托在我认为,就是一系列格式相同的方法列表,可能就是定义的名称不一致,参数.返回值等都是一样的. 2.如何声明委托 delegate void MyF ...

  4. PLSA中的EM算法

    转自:http://www.cnblogs.com/rocketfan/archive/2011/07/03/2096953.html 主要记录下几个文章博客内容 A Note on EM Algor ...

  5. .Net项目版本号的生成

    给.Net项目编译的程序集加入版本号的方式有许多种,包括: 1. 默认的方式,在每个项目的AssemblyInfo.cs文件中指定版本号: // Version information for an ...

  6. EF小节

    EF学习笔记——生成自定义实体类 http://blog.csdn.net/leftfist/article/details/24889819 --工具: 1.entity developer 2.D ...

  7. 如何设置box shadow的透明度

    (从已经死了一次又一次终于挂掉的百度空间人工抢救出来的,发表日期2014-04-24) 今天发现使用box-shadow属性,可以很好的给div添加阴影效果,但是添加的效果如果是: -moz-box- ...

  8. Failed to issue method call: Unit mysqld.service failed to load: No such file or directory.

    国内私募机构九鼎控股打造APP,来就送 20元现金领取地址:http://jdb.jiudingcapital.com/phone.html内部邀请码:C8E245J (不写邀请码,没有现金送)国内私 ...

  9. Android实现静默安装与卸载

    一般情况下,Android系统安装apk会出现一个安装界面,用户可以点击确定或者取消来进行apk的安装. 但在实际的项目需求中,有一种需求,就是希望apk在后台安装(不出现安装界面的提示),这种安装方 ...

  10. myeclipse如何导入相应的jar包

    方法一: 相应的项目------>右键------->build path-------->Config BuildPath...------->Libraries------ ...