正在看《第一行代码》,记录一下使用 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. visualC/C++连接MySql数据库

    vs连接数据库其实就是将mysql数据库.h头文件接口.lib链接文件和dll执行文件加入到项目中.下面是配置如何加入. 转于http://www.cnblogs.com/justinzhang/ar ...

  2. POJ1837 Balance(DP)

    POJ1837http://poj.org/problem?id=1837 题目大意就是说有一个称上有C个挂钩,告诉你每个挂钩的位置,现在有G个重物,求是之平衡的方法数. 转化一下:DP[i][j]表 ...

  3. LeetCode 刷题记录

    写在前面:因为要准备面试,开始了在[LeetCode]上刷题的历程.LeetCode上一共有大约150道题目,本文记录我在<http://oj.leetcode.com>上AC的所有题目, ...

  4. VS2010 用WebBrowser控件 无响应

    问题:偶尔我遇到这个问题,不知怎么的,拖放这个web控件它就卡死,无法响应,其他应用程序没有影响,任务管理器显示无法响应. 解决:原来是有道翻译的问题,具体为什么不清楚,只要一打开有道翻译,用web控 ...

  5. 【转】Android-Universal-Image-Loader 图片异步加载类库的使用(超详细配置)

    Android-Universal-Image-Loader 原文地址:http://blog.csdn.net/vipzjyno1/article/details/23206387 这个图片异步加载 ...

  6. mysql修改用户密码 新增用户

    修改密码: mysql> grant all privileges on *.* to yongfu_b@'192.168.1.%' identified by 'my_password_new ...

  7. SCROLLINFO结构体中fMask和nPage的理解

    还是VC++中有关显示图像的问题. 我们在显示一幅比较大的图像时,要使用带标准滚动条的对话框.涉及对滚动条的操作就不得不提SCROLLINFO这个结构体.只看单词意思就这道这个结构体要储存滚动条的一些 ...

  8. Putty 工具 保存配置的 小技巧

    用Putty 已经很长时间了,但一直被一个问题困扰,有时候是懒得去弄,反正也不怎么碍事,今天小研究了下,把这个问题解决了,心里也舒服了. Putty是一个免费小巧的Win32平台下的telnet,rl ...

  9. PostgreSQL没有redo log multiplexing

    与Oracle不同的是,PostgreSQL中压根没有这种的东西. 若以,如果因为写在线WAL文件是发生磁盘I/O错误,那么数据库系统就启动不了了. 解决的办法,我想,在PostgreSQL中,如论如 ...

  10. SharePoint 2013 中使用 JavaScript Like 和Unlike list item/page/document

    SharePoint 2013中新增了很多社交功能,比如用户可以like/unlike 任何一个 list item/page/document,这是一个非常不错的功能. 但有时觉得like/unli ...