Android 用HttpURLConnection访问网络的方法

一、 HttpURLConnection以GET方式访问网络:

HttpURLConnection connection = null;
try {
 URL url = new URL("https://www.xxx.com/");
 connection = (HttpURLConnection) url.openConnection();
 connection.setRequestMethod("GET");//设置访问方式为“GET”
 connection.setConnectTimeout(8000);//设置连接服务器超时时间为8秒
 connection.setReadTimeout(8000);//设置读取服务器数据超时时间为8秒

 if (HttpURLConnection.HTTP_OK == connection.getResponseCode()) {
  //从服务器获取响应并把响应数据转为字符串打印
  InputStream in = connection.getInputStream();
  BufferedReader reader = new BufferedReader(new InputStreamReader(in));

  StringBuilder response = new StringBuilder();
  String line;
  while (null != (line = reader.readLine())) {
    response.append(line);
  }
  Log.d(TAG, response.toString());
 }
} catch (Exception e) {
 e.printStackTrace();
} finally {
 if (null!= connection) {
   connection.disconnect();
 }
}

二、 HttpURLConnection以POST方式访问网络:

HttpURLConnection connection = null;
  try{
   URL url = new URL("https://www.xxx.com/");
   connection = (HttpURLConnection) url.openConnection();

   connection.setRequestMethod("POST");
   connection.setConnectTimeout(8000);
   connection.setReadTimeout(8000);
   connection.setDoOutput(true);// 使用 URL 连接进行输出
   connection.setDoInput(true);// 使用 URL 连接进行输入
   connection.setUseCaches(false);// 忽略缓存

   // 建立输出流,并写入数据
   OutputStream outputStream = connection.getOutputStream();
   DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
   dataOutputStream.writeBytes("username=admin&password=888888");
   dataOutputStream.close();

   if (HttpURLConnection.HTTP_OK == connection.getResponseCode()) {
    // 当正确响应时处理数据
    StringBuffer response = new StringBuffer();
    String line;
    BufferedReader responseReader =
      new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
    // 处理响应流,必须与服务器响应流输出的编码一致
    while (null != (line = responseReader.readLine())) {
     response.append(line);
    }
    responseReader.close();
    Log.d(TAG, response.toString());
   }

  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   if (null!= connection) {
    connection.disconnect();
   }
  }

注意:

1. HTTP访问是不允许在主线程进行的,否则会报错。因此上面的操作应该在新线程中进行。

2. 一般要用HttpURLConnection.getResponseCode() == 200来判断是否正常响应。为true则正常响应。

3. 在Android 2.2及以下版本,使用的是HttpClient,Android 2.3及以上版本,使用的是HttpURLConnection,而Android5.1之后废弃了HttpClient的相关Api。因此HttpClient用法不再进行研究。

4. 以POST方式提交数据时,每条数据要以键值对的方式提交,各条数据之间以&隔开。比如上面的代码中dataOutputStream.writeBytes(“username=admin&password=888888”);

5. 上面用到了StringBuilder和StringBuffer,没有什么特别用意,只是顺便用下。StringBuilder在单线程下比StringBuffer更高效,但不是线程安全的。

以上这篇Android 用HttpURLConnection访问网络的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • Android开发之HTTP访问网络

    本文实例为大家详细介绍了Android开发之HTTP访问网络的相关代码,供大家参考,具体内容如下 代码1: package com.ywhttpurlconnection; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; public class Ywhttpur

  • Android开发使用URLConnection进行网络编程详解

    本文实例讲述了Android开发使用URLConnection进行网络编程.分享给大家供大家参考,具体如下: URL的openConnection()方法将返回一个URLConnection,该对象表示应用程序和URL之间的通信连接,程序可以通过URLConnection实例向该URL发送请求,读取URL引用的资源.通常创建一个和URL的连接,并发送请求,读取此URL引用的资源. 需要如下步骤: a)通过调用URL对象openConnection()方法来创建URLConnection对象 b)

  • Android网络技术HttpURLConnection详解

    介绍 早些时候,Android 上发送 HTTP 请求一般有 2 种方式:HttpURLConnection 和 HttpClient.不过由于 HttpClient 存在 API 数量过多.扩展困难等缺点,Android 团队越来越不建议我们使用这种方式.在 Android 6.0 系统中,HttpClient 的功能被完全移除了.因此,在这里我们只简单介绍HttpURLConnection 的使用. 代码 (核心部分,目前只演示 GET 请求): 1. Manifest.xml 中添加网络权

  • Android开发使用HttpURLConnection进行网络编程详解【附源码下载】

    本文实例讲述了Android开发使用HttpURLConnection进行网络编程.分享给大家供大家参考,具体如下: --HttpURLConnection URLConnection已经可以非常方便地与指定站点交换信息,URLConnection下还有一个子类:HttpURLConnection,HttpURLConnection在URLConnection的基础上进行改进,增加了一些用于操作HTTP资源的便捷方法. setRequestMethod(String):设置发送请求的方法 get

  • Android通过HttpURLConnection和HttpClient接口实现网络编程

    Android中提供的HttpURLConnection和HttpClient接口可以用来开发HTTP程序.以下是学习中的一些经验. 1.HttpURLConnection接口 首先需要明确的是,Http通信中的POST和GET请求方式的不同.GET可以获得静态页面,也可以把参数放在URL字符串后面,传递给服务器.而POST方法的参数是放在Http请求中.因此,在编程之前,应当首先明确使用的请求方法,然后再根据所使用的方式选择相应的编程方式.HttpURLConnection是继承于URLCon

  • Android中HttpURLConnection与HttpClient的使用与封装

    1.写在前面 大部分andriod应用需要与服务器进行数据交互,HTTP.FTP.SMTP或者是直接基于SOCKET编程都可以进行数据交互,但是HTTP必然是使用最广泛的协议.     本文并不针对HTTP协议的具体内容,仅探讨android开发中使用HTTP协议访问网络的两种方式--HttpURLConnection和HttpClient     因为需要访问网络,需在AndroidManifest.xml中添加如下权限 <uses-permission android:name="an

  • Android 用HttpURLConnection访问网络的方法

    一. HttpURLConnection以GET方式访问网络: HttpURLConnection connection = null; try { URL url = new URL("https://www.xxx.com/"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET");//设置访问方式为"GET" co

  • Android Http协议访问网络实例(3种)

    之前关于Android Http协议访问网络的一点分析,最近需要回顾,就顺便发到随笔上了 Android中http连接主要是为了获取网络数据,目前了解的有3种方法: Httpconnection --本人常用 OKHTTP--看见过(需要在依赖中引入包) HttpClient--过气的方法(弃用) HTTPCONNECTION 由于网络连接是耗时操作不能在UI线程操作,一般通过Handler获取子线程中获取的数据 Handler mhandler=new Handler(){ @Override

  • Android实现授权访问网页的方法

    本文实例讲述了Android授权访问网页的实现方法,即使用Webview显示OAuth Version 2.a ImplicitGrant方式授权的页,但是对于移动终端不建议使用Authorize code grant方式授权. 具体功能代码如下所示: import android.annotation.SuppressLint; import android.app.Activity; import android.content.Intent; import android.graphics

  • asp.net访问网络路径方法(模拟用户登录)

    核心代码: public class IdentityScope : IDisposable { // obtains user token [DllImport("advapi32.dll", SetLastError = true)] static extern bool LogonUser(string pszUsername, string pszDomain, string pszPassword,int dwLogonType, int dwLogonProvider, r

  • Golang+Android基于HttpURLConnection实现的文件上传功能示例

    本文实例讲述了Golang+Android基于HttpURLConnection实现的文件上传功能.分享给大家供大家参考,具体如下: 这里要演示的是使用Android程序作为客户端(使用HttpURLConnection访问网络),Golang程序作为服务器端,实现文件上传. 客户端代码: public static String uploadFile(String uploadUrl, String filePath) { Log.v(TAG, "url:" + uploadUrl)

  • Android中实现地址栏输入网址能浏览该地址网页源码并操作访问网络

     首先实现简单布局: 复制代码 代码如下: <EditText android:id="@+id/et_url" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentRight="true&q

  • Android中ImageView使用网络图片资源的方法

    本文实例讲述了Android中ImageView使用网络图片资源的方法.分享给大家供大家参考.具体如下: 很多时候我们不想把东西都放在APK里面,或者是不能放进去,这时候我们就需要万能的网路帮助自己实现了 运行效果截图如下: java代码如下: package com.android.antking.imageview; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.Malformed

  • Android 监听网络状态方法详解

    Android 监听网络状态方法详解 一.加入网络权限 获取网络信息需要在AndroidManifest.xml文件中加入相应的权限. <uses-permission Android:name="android.permission.ACCESS_NETWORK_STATE" /> 二.判断手机网络的几个方案 1)判断是否有网络连接 public boolean isMobileConnected(Context context) { if (context != nul

随机推荐