正在看《第一行代码》,记录一下使用 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. TQImport3XLS.Map

    property Map: TStrings; 设置数据集字段和Excel单元格之间定义映射属性以下列方式: FieldName=CellRange 导入单独的单元格 Field1=A1 Field1 ...

  2. mv命令

    mv命令是move的缩写,可以用来移动文件或者将文件改名(move (rename) files),是Linux系统下常用的命令,经常用来备份文件或者目录. 1.命令格式: mv [选项] 源文件或目 ...

  3. Eclipse报错 Unable to execute dex: Multiple dex files define Lcom/kenai/jbosh/AbstractAttr

    这个错误时jar包重复造成的!! 看看有没有多的private Libary  删除即可!!!

  4. JavaScript escape encodeURI encodeURIComponent() 函数

    总结一下: 1.encodeURI(),和encodeURIComponent()是对字符进行编码. 2.decodeURI(),和decodeURIComponent()是对相应编码过的字符进行解码 ...

  5. hdu1213 How Many Tables

    How Many Tables Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) ...

  6. 前向否定界定符 python正则表达式不匹配某个字符串 以及无捕获组和命名组(转)

    [编辑] 无捕获组和命名组 精心设计的 REs 也许会用很多组,既可以捕获感兴趣的子串,又可以分组和结构化 RE 本身.在复杂的 REs 里,追踪组号变得困难.有两个功能可以对这个问题有所帮助.它们也 ...

  7. U8记账凭证修改方法汇总

    在输入记账凭证时,尽管账务系统提供了多种控制错误的措施,但错误凭证的出现是难免的,为此,系统必须能够提供对错误凭证修改的功能.目前,许多财 务软件(如:用友.安易.三门)都提供了“反审核.反记账.反结 ...

  8. Linux Kconfig及Makefile学习

    内核源码树的目录下都有两个文档Kconfig (2.4版本是Config.in)和Makefile.分布到各目录的Kconfig构成了一个分布式的内核配置数据库,每个Kconfig分别描述了所属目录源 ...

  9. hdu 5591 ZYB's Game 博弈论

    ZYB's Game Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://acm.hdu.edu.cn/showproblem.php?pid=55 ...

  10. 搭建Spring + SpringMVC + Mybatis框架之三(整合Spring、Mybatis和Spring MVC)

    整合Spring和SpringMVC 之前已经整合了spring和mybatis,现在在此基础上整合SSM. 项目目录: 思路:SpringMVC的配置文件独立,然后在web.xml中配置整合. (1 ...