正在看《第一行代码》,记录一下使用 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. hdoj 1404 Digital Deletions(博弈论)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1404 一看就是博弈论的题目,但并没有什么思路,看了题解,才明白 就是求六位数的SG函数,暴力一遍,打表 ...

  2. iOS7 各种问题解决

    1 UITableView 行分割线不到头,短线问题 if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) { ...

  3. 免费的天气Web Service接口

    免费的天气Web Service接口 在android应用当中很多时候需要获取天气的信息,这里提供怎么获取天气信息: 1. http://www.ayandy.com/Service.asmx?wsd ...

  4. document.body为null的问题

    虽然body是JS中的DOM技术中所有浏览器支持的属性,但在我们的代码编写中,还是会碰到document.is null问题 例如:我们可以使用alert(document.body);的时候,就会提 ...

  5. Spket在Eclipse/MyEclipse下的安装和配置(图文教程)

    一.安装Spket 第一种方法:网上更新方式 1.插件首页:http://www.spket.com2.插件名称:Spket IDE3.更新连接(Update Site):http://www.spk ...

  6. 实战项目:通过当当API将订单抓取到SAP(一)

    公司在当当上经营了一家店铺,通过当当提供的API,用C#写代码,通过NCO3.0调用SAP RFC将订单信息抓取到SAP. 如果你是新手,在当当网上有店铺,且你公司使用SAP系统,恭喜你,下面这些代码 ...

  7. Codeforces Round #245 (Div. 1) 429D - Tricky Function 最近点对

    D. Tricky Function Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 codeforces.com/problemset/problem/42 ...

  8. cdoj 1150 排名表 拓扑排序

    排名表 Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://acm.uestc.edu.cn/#/problem/show/1150 Descrip ...

  9. 搭建Spring + SpringMVC + Mybatis框架之二(整合Spring和Mybatis)

    整合Spring和Mybatis 首先给出完整的项目目录: (1)引入项目需要的jar包 使用http://maven.apache.org作为中央仓库即可. Spring核心包,mybatis核心包 ...

  10. C++进制转换(十进制转二进制、八进制、随意进制)

    十进制转二进制: //十进制转二进制 #include<iostream> using namespace std; void printbinary(const unsigned int ...