这边只考虑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请求
dowanload demo 单线程下载 断点下载,简单好用的下载工具 使用原生HttpUrlConnection AsyncTask 模仿手机应用市场
一个基于Java原生的Http客户端。HttpNet网络请求框架基于HttpUrlConnection
Java原生HttpUrlConnection访问WebService实例,附相关jar包...新手整理不喜勿喷
此代码为网络请求的工具类 包含原生的HttpClient 、HttpUrlConnection以及Xutils 和Volley框架的网络请求。
Android网络框架之OkHttp是一个...OkHttp不仅在接口封装上画面做的简单易用,就连在底层实现上也是自成一派,比起原生的HttpURLConnection可以说是有过之而无不及,现在已经成了广大Android开发者首选的网络通信库。
本文目录第一步:添加网络访问权限第二步:使用HttpURLConnection访问网络代码示例 Android原生目前支持两种方式访问http协议的网络,第一种是HttpURLConnection,另外一种是oKHttp,下面来介绍一下用...
HTTP 请求一般采用原生的 HttpClient 和 HttpUrlConnection 的两种网络访问方式。可是在 Android 5.0 的时候 Google 就不推荐使用 HttpClient 了,到了 Android 6.0 (api 23) SDK,不再提供 org.apache.http.* (只...
使用 HttpUrlConnection 类发送 HTTP 请求,接着使用 Jsoup 对响应的 HTML 页面进行解析,获取我们想要的数据。最后,我们将获取的数据存储到数据库中,这里使用了 Mybatis-Plus 提供的 insert 方法。
Android客户端向服务器端请求数据的两种主要方式:HTTPURLConnection、HTTPClient;内含客户端与服务器端Demo(带有详细注释),原生方式解析json数据,希望大家多多批评指教!!
A HttpNetClient for Java or Android.一个基于Java原生的Http客户端。HttpNet网络请求框架基于HttpUrlConnection,采用Client Request Call的请求模型,后续将会实现 Https、队列、缓存模块
HttpCilent 跟 HttpURLConnection 是安卓原生的用来实现http请求的类: Android 6.0之后取消了HttpClient,不支持跟新 ,今天小编使用的是HttpURLConnection : 直接上代码: URL url = null; ...