`
xuanzhui
  • 浏览: 199526 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类
最新评论

使用原生的HttpURLConnection库进行网络请求

阅读更多

这边只考虑json格式轻量级的数据请求。

 

除了部分像Build.VERSION.SDK_INT这样的只属于android的sdk API,其他是java通用。

 

URL openConnection获取的URLConnection实例由平台和http类型决定,比如安卓从4.4版本开始,http的url底层为com.android.okhttp.internal.http.HttpURLConnectionImpl,如果url是https的那么对应的是HttpsURLConnectionImpl

 

对于Http(s)URLConnection,如果服务器返回的是正常的结果,那么对应的数据可以通过getInputStream获取;但是如果服务器返回的不是正常的结果,例如400,那么需要通过getErrorStream获取详细错误信息。以下的处理是直接通过捕捉IOException处理的,也可以通过getResponseCode先判断服务器状态,比如

HttpURLConnection httpConn = (HttpURLConnection)connection;
InputStream is;
if (httpConn.getResponseCode() >= 400) {
    is = httpConn.getErrorStream();
} else {
    is = httpConn.getInputStream();
}

 

完整的请求

/**
 * http get 请求
 * @param url   请求uri
 * @return      HttpResponse请求结果实例
 */
public static Response httpGet(String url) {

    Response response = null;

    HttpURLConnection httpURLConnection = null;
    try {
        URL urlObj = new URL(url);

        httpURLConnection = (HttpURLConnection) urlObj.openConnection();

        httpURLConnection.setConnectTimeout(XZCache.getInstance().connectTimeout);
        httpURLConnection.setReadTimeout(XZCache.getInstance().readTimeout);

        httpURLConnection.setDoInput(true);

        // 4.0 ~ 4.3 存在EOFException
        if (Build.VERSION.SDK_INT > 13 && Build.VERSION.SDK_INT < 19) {
            httpURLConnection.setRequestProperty("Connection", "close");
        }

        response = readStream(httpURLConnection);

    } catch (MalformedURLException e) {
        e.printStackTrace();

        response = new Response();
        response.content = e.getMessage();
        response.code = -1;
    } catch (IOException e) {
        e.printStackTrace();

        response = new Response();
        response.content = e.getMessage();
        response.code = -1;
    } catch (Exception ex) {
        ex.printStackTrace();
        response = new Response();
        response.content = ex.getMessage();
        response.code = -1;
    } finally {
        if (httpURLConnection != null)
            httpURLConnection.disconnect();
    }

    return response;
}

static Response readStream(HttpURLConnection connection) {
    Response response = new Response();
    
    StringBuilder stringBuilder = new StringBuilder();

    BufferedReader reader = null;
    try {

        reader = new BufferedReader(new InputStreamReader(
                connection.getInputStream(), "UTF-8"));

        int tmp;
        while ((tmp = reader.read()) != -1) {
            stringBuilder.append((char)tmp);
        }

        response.code = connection.getResponseCode();
        response.content = stringBuilder.toString();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        response.code = -1;
        response.content = e.getMessage();
    } catch (IOException e) {
        e.printStackTrace();

        try {
            //it could be caused by 400 and so on

            reader = new BufferedReader(new InputStreamReader(
                    connection.getErrorStream(), "UTF-8"));

            //clear
            stringBuilder.setLength(0);

            int tmp;
            while ((tmp = reader.read()) != -1) {
                stringBuilder.append((char)tmp);
            }

            response.code = connection.getResponseCode();
            response.content = stringBuilder.toString();

        } catch (IOException e1) {
            response.content = e1.getMessage();
            response.code = -1;
            e1.printStackTrace();
        } catch (Exception ex) {
            //if user directly shuts down network when trying to write to server
            //there could be NullPointerException or SSLException
            response.content = ex.getMessage();
            response.code = -1;
            ex.printStackTrace();
        }
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return response;
}

//return null means successfully write to server
static Response writeStream(HttpURLConnection connection, String content) {
    BufferedOutputStream out=null;
    Response response = null;
    try {
        out = new BufferedOutputStream(connection.getOutputStream());
        out.write(content.getBytes("UTF-8"));
        out.flush();
    } catch (IOException e) {
        e.printStackTrace();

        try {
            //it could be caused by 400 and so on
            response = new Response();

            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    connection.getErrorStream(), "UTF-8"));

            StringBuilder stringBuilder = new StringBuilder();

            int tmp;
            while ((tmp = reader.read()) != -1) {
                stringBuilder.append((char)tmp);
            }

            response.code = connection.getResponseCode();
            response.content = stringBuilder.toString();

        } catch (IOException e1) {
            response = new Response();
            response.content = e1.getMessage();
            response.code = -1;
            e1.printStackTrace();
        } catch (Exception ex) {
            //if user directly shutdowns network when trying to write to server
            //there could be NullPointerException or SSLException
            response = new Response();
            response.content = ex.getMessage();
            response.code = -1;
            ex.printStackTrace();
        }
    } finally {
        try {
            if (out!=null)
                out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return response;
}

/**
 * http post 请求
 * @param url       请求url
 * @param jsonStr    post参数
 * @return          HttpResponse请求结果实例
 */
public static Response httpPost(String url, String jsonStr) {
    Response response = null;

    HttpURLConnection httpURLConnection = null;
    try {
        URL urlObj = new URL(url);

        httpURLConnection = (HttpURLConnection) urlObj.openConnection();

        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setConnectTimeout(XZCache.getInstance().connectTimeout);
        httpURLConnection.setReadTimeout(XZCache.getInstance().readTimeout);
        httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setChunkedStreamingMode(0);

        // 4.0 ~ 4.3 存在EOFException
        if (Build.VERSION.SDK_INT > 13 && Build.VERSION.SDK_INT < 19) {
            httpURLConnection.setRequestProperty("Connection", "close");
        }

        //start to post
        response = writeStream(httpURLConnection, jsonStr);

        if (response == null) { //if post successfully

            response = readStream(httpURLConnection);

        }
    } catch (MalformedURLException e) {
        e.printStackTrace();

        response = new Response();
        response.content = e.getMessage();
        response.code = -1;
    } catch (IOException e) {
        e.printStackTrace();

        response = new Response();
        response.content = e.getMessage();
        response.code = -1;
    } catch (Exception ex) {
        ex.printStackTrace();
        response = new Response();
        response.content = ex.getMessage();
        response.code = -1;
    } finally {
        if (httpURLConnection != null)
            httpURLConnection.disconnect();
    }

    return response;
}

public static class Response {
    public Integer code;
    public String content;
}

 

 

 

 

 

分享到:
评论

相关推荐

    android使用Java原生httpUrlConnection进行get请求

    总结一下,Android中使用Java原生HttpURLConnection进行GET请求涉及以下关键点: - 创建URL对象并获取HttpURLConnection实例。 - 设置请求方法和相关属性,如超时和User-Agent。 - 检查响应状态码,处理成功或错误...

    原生代码实现网络请求

    本篇将详细探讨如何使用Android原生API来执行网络请求,主要涉及URL类、HttpURLConnection类以及Socket编程。 首先,`URL`类是Java中的基础网络类,它用于解析和表示统一资源定位符(Uniform Resource Locator)。...

    使用JAVA原生实现简单的HTTP请求

    在Java编程语言中,发送HTTP请求是常见的网络通信任务,主要用到的是`java.net.URL`和`java.net.HttpURLConnection`这两个核心类。本篇将详细介绍如何使用Java原生API实现简单的HTTP请求。 首先,我们需要了解HTTP...

    一个基于Java原生的Http客户端。HttpNet网络请求框架基于HttpUrlConnection.zip

    Java原生的Http客户端是Java标准库中提供的一种基础网络通信工具,主要通过HttpURLConnection类进行网络请求。HttpNet网络请求框架就是基于这个类构建的一个轻量级、高效的网络请求库。在Java开发中,...

    Android-kotlin实现网络请求库

    5. **网络请求库的设计**: 自定义网络请求库通常会包含以下几个核心部分:请求接口(定义请求方法和URL)、网络请求实现(使用HttpURLConnection或OkHttp等)、数据解析(使用Fastjson或其他解析库)、线程管理...

    Android-从android原生角度理解网络请求和异步操作

    Android支持多种网络请求库,如OkHttp、Volley、Retrofit等,但原生支持的是`HttpURLConnection`。`HttpURLConnection`是Java提供的标准API,用于与HTTP服务器通信。它的优点在于轻量级、低资源消耗,并且支持...

    Android 网络请求的那些事Demo

    1. HttpURLConnection:原生Android库,轻量级且低级,适合定制化需求,但使用相对复杂。 2. HttpClient(已废弃):虽然在新版本中被废弃,但在某些旧项目中仍然使用。 3. OkHttp:高效且易用的第三方库,支持...

    android 网络请求封装

    - Android原生提供了HttpURLConnection,但使用起来较为繁琐。开发者通常选择Apache HttpClient或OkHttp作为网络请求库,因为它们提供更高级别的API,易于使用且性能优越。 3. **Retrofit**: - Retrofit是Square...

    网络请求工具类

    本篇将详细解析"网络请求工具类"所涵盖的知识点,包括原生的HttpClient、HttpUrlConnection、Xutils以及Volley框架的网络请求。 1. **原生的HttpClient** Android原生支持的HttpClient库是Apache HttpClient,它...

    HttpUrlConnection请求WebService.rar

    以上就是使用Java原生的HttpURLConnection访问WebService的基本流程。这个例子适合初学者,因为它是Java标准库的一部分,无需额外依赖。然而,在实际项目中,由于HttpURLConnection的API相对复杂,开发者往往会选择...

    Android Studio发起GET网络请求

    虽然原生的HttpURLConnection可以满足基本需求,但使用第三方库如OkHttp会更高效、更易用。首先,在build.gradle文件中添加依赖: ```groovy dependencies { implementation 'com.squareup.okhttp3:okhttp:4.9.3' }...

    android原生post请求源码

    在Android开发中,进行网络通信是常见的需求,而POST请求是一种常用的数据提交方式。本教程将深入探讨如何在Android原生环境中实现POST请求,并通过源码解析来理解其工作原理。 首先,Android中的网络操作主要依赖...

    Android 网络请求

    本示例聚焦于使用HTTPURLConnection进行GET请求,这是一种基础且常用的网络请求方法。在Android中,由于安全性和权限管理的原因,进行网络操作时必须遵循特定的步骤。 首先,我们需要在`AndroidManifest.xml`文件中...

    httpurlconnection 获取服务器数据并解析

    在Android开发中,HTTPURLConnection是Java标准库提供的一种与服务器进行HTTP通信的API,它是HttpClient的一个轻量级替代方案,适用于简单的HTTP请求。本篇将深入讲解如何使用HTTPURLConnection获取服务器数据并进行...

    Android网络请求框架

    2. Retrofit:由Square公司开发,它通过注解的方式将网络接口映射到HTTP请求,结合Gson等库可以方便地进行数据序列化和反序列化,适合构建RESTful API的网络请求。 3. OkHttp:同样来自Square,是一个高效的HTTP...

    Android课件(URL+HttpURLConnection).zip

    - 尽管HttpURLConnection是原生支持的,但现代的Android开发更多倾向于使用Retrofit、OkHttp等第三方库,它们提供了更简洁、强大的网络请求功能。 以上就是关于Android中URL和HttpURLConnection的相关知识点。通过...

    curl库做http请求

    在Android平台上,虽然原生SDK提供了HttpURLConnection和OkHttp等API来处理网络请求,但有些开发者仍然选择使用curl库,因为它提供了更灵活的选项和控制。 curl库的核心功能在于它的命令行工具,可以处理复杂的HTTP...

    java android httpURLConnection的封装

    然而,原生的HttpURLConnection类使用起来比较繁琐,因此对其进行封装可以让使用者更简单、方便地进行HTTP请求的发送与接收。 封装httpURLConnection的主要目的是简化网络请求的处理流程,包括设置请求参数、添加...

    xamarin学习笔记A16(安卓OkHttp3和HttpURLConnection)下

    同样,也可以直接调用Android SDK中的HttpURLConnection接口进行网络请求。对于Xamarin开发者来说,理解这两种网络请求方式的优缺点和使用场景,将有助于提升应用的质量和性能。 在提供的压缩包文件中,可能包含的...

Global site tag (gtag.js) - Google Analytics