Android http 的使用
1、okHttp
https://github.com/square/okhttp
2、okhttp-utils
https://github.com/hongyangAndroid/okhttp-utils
3、NoHttp
https://github.com/yanzhenjie/NoHttp
4、okhttp-OkGo
https://github.com/jeasonlzy/okhttp-OkGo
5、最原生的http
package www.yiba.com.wifisdk.http; import android.os.Build; import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection; import javax.net.ssl.HttpsURLConnection; public class HttpUtil { private static final int TIMEOUT_IN_MILLIONS = 25000; /**
* Get请求,获得返回数据
* @param urlStr
* @return
* @throws Exception
*/
public static String doGet(String urlStr , Callback callback) {
URL url = null;
URLConnection conn = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
url = new URL(urlStr);
int responseCode = -1;
if (urlStr.toLowerCase().startsWith("https")) {
conn = url.openConnection();
((HttpsURLConnection) conn).setRequestMethod("GET");
conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
if (Build.VERSION.SDK != null
&& Build.VERSION.SDK_INT > 13) {//http://www.tuicool.com/articles/7FrMVf
conn.setRequestProperty("Connection", "close");
}
responseCode = ((HttpsURLConnection) conn).getResponseCode();
} else {
conn = url.openConnection();
((HttpURLConnection) conn).setRequestMethod("GET");
conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
if (Build.VERSION.SDK != null
&& Build.VERSION.SDK_INT > 13) {//http://www.tuicool.com/articles/7FrMVf
conn.setRequestProperty("Connection", "close");
}
responseCode = ((HttpURLConnection) conn).getResponseCode();
}
if (responseCode == 200) {
is = conn.getInputStream();
baos = new ByteArrayOutputStream();
int len = -1;
byte[] buf = new byte[128]; while ((len = is.read(buf)) != -1) {
baos.write(buf, 0, len);
}
baos.flush();
if ( callback != null ){
callback.ok( baos.toString() );
}
return baos.toString();
} else {
if ( callback != null ){
callback.fail();
}
throw new RuntimeException(" responseCode is not 200 ... ");
} } catch (Exception e) {
if ( callback != null ){
callback.timeOut();
}
e.printStackTrace();
} finally {
try {
if (is != null)
is.close();
} catch (IOException e) {
}
try {
if (baos != null)
baos.close();
} catch (IOException e) {
}
if (conn != null) {
if (urlStr.toLowerCase().startsWith("https")) {
((HttpsURLConnection) conn).disconnect();
} else {
((HttpURLConnection) conn).disconnect();
}
}
}
return null;
} public static String doPost(String url, String param , Callback callback ) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
URLConnection conn = null;
try {
URL realUrl = new URL(url);
//打开和URL之间的连接
conn = realUrl.openConnection();
//设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
if (url.toLowerCase().startsWith("https")) {
((HttpsURLConnection) conn).setRequestMethod("POST");
} else {
((HttpURLConnection) conn).setRequestMethod("POST");
}
conn.setRequestProperty("charset", "utf-8");
conn.setUseCaches(false);
//发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
conn.setConnectTimeout(TIMEOUT_IN_MILLIONS); if (param != null && !param.trim().equals("")) {
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
} int responseCode = ((HttpURLConnection) conn).getResponseCode();
if ( responseCode == 200 ){
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
} if ( callback != null ){
callback.ok( result );
}
}else {
if ( callback != null ){
callback.fail();
}
}
} catch (Exception e) {
if ( callback != null ){
callback.timeOut();
}
e.printStackTrace();
}
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
if (conn != null) {
if (url.toLowerCase().startsWith("https")) {
((HttpsURLConnection) conn).disconnect();
} else {
((HttpURLConnection) conn).disconnect();
}
}
}
return result;
} public interface Callback{
void ok( String result ) ;
void fail();
void timeOut() ;
} }
6、对原生http的简易封装
6.1 HttpCall http 请求结果的实体类
package www.yiba.com.analytics.http; /**
* Created by ${zyj} on 2016/8/18.
*/
public class HttpCall { private ResponseType httpQuestType ;
private String result ; public ResponseType getHttpQuestType() {
return httpQuestType;
} public void setHttpQuestType(ResponseType httpQuestType) {
this.httpQuestType = httpQuestType;
} public String getResult() {
return result;
} public void setResult(String result) {
this.result = result;
}
}
6.2 ResponseType http 请求结果的类型
package www.yiba.com.analytics.http; /**
* Created by ${zyj} on 2016/8/18.
*/
public enum ResponseType { OK("请求成功") , FAIL("请求失败") , TIMEOUT("请求超时") ; private String name ; private ResponseType(String name ){
this.name = name ;
} public String getName() {
return name;
}
}
6.3 HttpUtil 包含 get 和 post请求
package www.yiba.com.analytics.http; import android.os.Build; import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection; import javax.net.ssl.HttpsURLConnection; public class HttpUtil { private static final int TIMEOUT_IN_MILLIONS = 25000; /**
* Get请求,获得返回数据
* @param urlStr
* @return
* @throws Exception
*/
public static HttpCall doGet(String urlStr , Callback callback) {
URL url = null;
URLConnection conn = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
HttpCall httpCall = new HttpCall() ; try {
url = new URL(urlStr);
int responseCode = -1;
if (urlStr.toLowerCase().startsWith("https")) {
conn = url.openConnection();
((HttpsURLConnection) conn).setRequestMethod("GET");
conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
if (Build.VERSION.SDK != null
&& Build.VERSION.SDK_INT > 13) {//http://www.tuicool.com/articles/7FrMVf
conn.setRequestProperty("Connection", "close");
}
responseCode = ((HttpsURLConnection) conn).getResponseCode();
} else {
conn = url.openConnection();
((HttpURLConnection) conn).setRequestMethod("GET");
conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
if (Build.VERSION.SDK != null
&& Build.VERSION.SDK_INT > 13) {//http://www.tuicool.com/articles/7FrMVf
conn.setRequestProperty("Connection", "close");
}
responseCode = ((HttpURLConnection) conn).getResponseCode();
}
if (responseCode == 200) {
is = conn.getInputStream();
baos = new ByteArrayOutputStream();
int len = -1;
byte[] buf = new byte[128]; while ((len = is.read(buf)) != -1) {
baos.write(buf, 0, len);
}
baos.flush();
if ( callback != null ){
callback.ok( baos.toString() );
}
if ( httpCall != null ){
httpCall.setHttpQuestType( ResponseType.OK );
httpCall.setResult( baos.toString() );
} } else {
if ( callback != null ){
callback.fail();
}
if ( httpCall != null ){
httpCall.setHttpQuestType( ResponseType.FAIL );
httpCall.setResult( "" );
}
} } catch (Exception e) {
if ( callback != null ){
callback.timeOut();
}
if ( httpCall != null ){
httpCall.setHttpQuestType( ResponseType.TIMEOUT );
httpCall.setResult( "" );
}
e.printStackTrace();
} finally {
try {
if (is != null)
is.close();
} catch (IOException e) {
}
try {
if (baos != null)
baos.close();
} catch (IOException e) {
}
if (conn != null) {
if (urlStr.toLowerCase().startsWith("https")) {
((HttpsURLConnection) conn).disconnect();
} else {
((HttpURLConnection) conn).disconnect();
}
} return httpCall ;
}
} public static HttpCall doPost(String url, String param , Callback callback ) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
URLConnection conn = null;
HttpCall httpCall = new HttpCall() ; try {
URL realUrl = new URL(url);
//打开和URL之间的连接
conn = realUrl.openConnection();
//设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Content-Type",
"application/json");
if (url.toLowerCase().startsWith("https")) {
((HttpsURLConnection) conn).setRequestMethod("POST");
} else {
((HttpURLConnection) conn).setRequestMethod("POST");
}
conn.setRequestProperty("charset", "utf-8");
conn.setUseCaches(false);
//发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
conn.setConnectTimeout(TIMEOUT_IN_MILLIONS); if (param != null && !param.trim().equals("")) {
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
} int responseCode = ((HttpURLConnection) conn).getResponseCode();
if ( responseCode == 200 ){
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
} if ( callback != null ){
callback.ok( result );
} if ( httpCall != null ){
httpCall.setHttpQuestType( ResponseType.OK );
httpCall.setResult( result );
} }else {
if ( callback != null ){
callback.fail();
}
if ( httpCall != null ){
httpCall.setHttpQuestType( ResponseType.FAIL );
httpCall.setResult( "" );
} }
} catch (Exception e) {
if ( callback != null ){
callback.timeOut();
}
if ( httpCall != null ){
httpCall.setHttpQuestType( ResponseType.TIMEOUT );
httpCall.setResult( "" );
}
e.printStackTrace();
}
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
if (conn != null) {
if (url.toLowerCase().startsWith("https")) {
((HttpsURLConnection) conn).disconnect();
} else {
((HttpURLConnection) conn).disconnect();
}
}
return httpCall ;
}
} public interface Callback{
void ok(String result) ;
void fail();
void timeOut() ;
} }
6.4 如何使用
private void httpGet(){
//get 用法1
new Thread(new Runnable() {
@Override
public void run() {
HttpUtil.doGet("http://www.baidu.com", new HttpUtil.Callback() {
@Override
public void ok(String result) {
//请求成功
}
@Override
public void fail() {
//请求失败
}
@Override
public void timeOut() {
//请求超时
}
}) ;
}
}) ;
//get 用法2
new Thread(new Runnable() {
@Override
public void run() {
HttpCall httpCall = HttpUtil.doGet( "http://www.baidu.com" , null ) ;
switch ( httpCall.getHttpQuestType() ){
case OK:
//请求成功
break;
case FAIL:
//请求失败
break;
case TIMEOUT:
//请求超时
break;
}
}
}) ;
}
private void httpPost(){
//post 用法1
new Thread(new Runnable() {
@Override
public void run() {
HttpUtil.doPost("http://www.baidu.com", "post请求参数" , new HttpUtil.Callback() {
@Override
public void ok(String result) {
//请求成功
}
@Override
public void fail() {
//请求失败
}
@Override
public void timeOut() {
//请求超时
}
}) ;
}
}) ;
//post 用法2
new Thread(new Runnable() {
@Override
public void run() {
HttpCall httpCall = HttpUtil.doPost( "http://www.baidu.com" , "post请求参数" , null ) ;
switch ( httpCall.getHttpQuestType() ){
case OK:
//请求成功
break;
case FAIL:
//请求失败
break;
case TIMEOUT:
//请求超时
break;
}
}
}) ;
}
7、http下载图片并且压缩bitmap
//从网络下载bitmap
private Bitmap downLoadBitmapFromNet( String urlString ){
InputStream inputStream = null ;
HttpURLConnection conn = null ;
Bitmap bitmap ;
try {
URL url = new URL( urlString ) ;
conn = (HttpURLConnection) url.openConnection();
inputStream = new BufferedInputStream( conn.getInputStream() ) ; inputStream.mark( inputStream.available() ); //压缩图片
BitmapFactory.Options options = new BitmapFactory.Options() ;
options.inJustDecodeBounds = true ;
BitmapFactory.decodeStream( inputStream , null , options ) ;
options.inSampleSize = 4 ;
options.inPreferredConfig = Bitmap.Config.RGB_565 ;
options.inJustDecodeBounds = false ; inputStream.reset();
bitmap = BitmapFactory.decodeStream( inputStream , null , options ) ; return bitmap ;
} catch (MalformedURLException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}finally {
if ( inputStream != null ){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if ( conn != null ){
conn.disconnect();
}
}
return null ;
}
需要注意的事项
1、并不是所有的inputStream都支持mark()方法的, 因为这里的 InputStream其实是 BufferedInputStream 。 BufferedInputStream 继承 InputStream 并且重写了里面的 mark() 、reset() 、markSupported()
Android http 的使用的更多相关文章
- 【原】Android热更新开源项目Tinker源码解析系列之三:so热更新
本系列将从以下三个方面对Tinker进行源码解析: Android热更新开源项目Tinker源码解析系列之一:Dex热更新 Android热更新开源项目Tinker源码解析系列之二:资源文件热更新 A ...
- 配置android sdk 环境
1:下载adnroid sdk安装包 官方下载地址无法打开,没有vpn,使用下面这个地址下载,地址:http://www.android-studio.org/
- Android SwipeRefreshLayout 下拉刷新——Hi_博客 Android App 开发笔记
以前写下拉刷新 感觉好费劲,要判断ListView是否滚到顶部,还要加载头布局,还要控制 头布局的状态,等等一大堆.感觉麻烦死了.今天学习了SwipeRefreshLayout 的用法,来分享一下,有 ...
- Android Studio配置 AndroidAnnotations——Hi_博客 Android App 开发笔记
以前用Eclicps 用习惯了现在 想学学 用Android Studio 两天的钻研终于 在我电脑上装了一个Android Studio 并完成了AndroidAnnotations 的配置. An ...
- Android请求网络共通类——Hi_博客 Android App 开发笔记
今天 ,来分享一下 ,一个博客App的开发过程,以前也没开发过这种类型App 的经验,求大神们轻点喷. 首先我们要创建一个Andriod 项目 因为要从网络请求数据所以我们先来一个请求网络的共通类. ...
- 【原】Android热更新开源项目Tinker源码解析系列之一:Dex热更新
[原]Android热更新开源项目Tinker源码解析系列之一:Dex热更新 Tinker是微信的第一个开源项目,主要用于安卓应用bug的热修复和功能的迭代. Tinker github地址:http ...
- 【原】Android热更新开源项目Tinker源码解析系列之二:资源文件热更新
上一篇文章介绍了Dex文件的热更新流程,本文将会分析Tinker中对资源文件的热更新流程. 同Dex,资源文件的热更新同样包括三个部分:资源补丁生成,资源补丁合成及资源补丁加载. 本系列将从以下三个方 ...
- Android Studio 多个编译环境配置 多渠道打包 APK输出配置
看完这篇你学到什么: 熟悉gradle的构建配置 熟悉代码构建环境的目录结构,你知道的不仅仅是只有src/main 开发.生成环境等等环境可以任意切换打包 多渠道打包 APK输出文件配置 需求 一般我 ...
- JS调用Android、Ios原生控件
在上一篇博客中已经和大家聊了,关于JS与Android.Ios原生控件之间相互通信的详细代码实现,今天我们一起聊一下JS调用Android.Ios通信的相同点和不同点,以便帮助我们在进行混合式开发时, ...
- Android UI体验之全屏沉浸式透明状态栏效果
前言: Android 4.4之后谷歌提供了沉浸式全屏体验, 在沉浸式全屏模式下, 状态栏. 虚拟按键动态隐藏, 应用可以使用完整的屏幕空间, 按照 Google 的说法, 给用户一种 身临其境 的体 ...
随机推荐
- iframe的内容增高或缩减时设置其iframe的高度的处理方案
WEB管理软件往往是如下结构的 用户点击子页tab切换中部的显示内容,在切换过程中需要保证前面的子页保持先前的状态.这种情况一般都使用iframe来来作为切换的子页显示内容. 但是这里有一个问题,if ...
- SQL Server中的事务日志管理(7/9):处理日志过度增长
当一切正常时,没有必要特别留意什么是事务日志,它是如何工作的.你只要确保每个数据库都有正确的备份.当出现问题时,事务日志的理解对于采取修正操作是重要的,尤其在需要紧急恢复数据库到指定点时.这系列文章会 ...
- SQL Server安全(8/11):数据加密(Data Encryption)
在保密你的服务器和数据,防备当前复杂的攻击,SQL Server有你需要的一切.但在你能有效使用这些安全功能前,你需要理解你面对的威胁和一些基本的安全概念.这篇文章提供了基础,因此你可以对SQL Se ...
- 12种JavaScript MVC框架之比较
Gordon L. Hempton是西雅图的一位黑客和设计师,他花费了几个月的时间研究和比较了12种流行的JavaScript MVC框架,并在博客中总结了每种框架的优缺点,最终的结果是,Ember. ...
- linux专题三之如何悄悄破解root密码(以redhat7.2x64为例)
root用户在linux系统中拥有至高无上的权限.掌握了root密码,差不对可以对linux系统随心所欲了,当然了,root用户也不是权限最高的用户. 但是掌握了root密码,基本上够我们用了.本文将 ...
- 使用MVVM-Sidekick开发Universal App(二)
上一篇文章已经建立了基本的实体类,并且搞定了多语言的问题,以后在app里用字符串的时候就可以从资源文件中取了.现在继续进行. 一.添加一个页面 CurrencyExchanger首页是一个货币兑换的列 ...
- ASP.NET MVC图片管理(更新)
Insus.NET在ASP.NET MVC专案中,实现了图片管理,上传,预览,显示,删除等功能,还差一个功能,就是更新图片的功能,那这次来完成它.你可以先参考前2篇<ASP.NET MVC图片管 ...
- HTML 5表单应用小结
本文内容 HTML 5表单的组织方式 HTML 5表单的新增特性 访问表单控件及响应表单控件事件 HTML 5表单的组织方式 ★ 将表单字段及其标签关联起 ...
- 不可或缺 Windows Native (18) - C++: this 指针, 对象数组, 对象和指针, const 对象, const 指针和指向 const 对象的指针, const 对象的引用
[源码下载] 不可或缺 Windows Native (18) - C++: this 指针, 对象数组, 对象和指针, const 对象, const 指针和指向 const 对象的指针, con ...
- 【Linux_Fedora_应用系列】_1_如何安装音乐播放器和mp3解码
因为安装环境的不同,Fedora在安装后会安装不同的软件包.通常在安装的时候有多种选择: 1.桌面环境: 适合个人日常使用,安装包含办公软件(Fedora 默认安装Open Office).娱乐影音软 ...