Android Studio 网络编程 OkHttp3 用法
来源:互联网 发布:可视化编程的最大优点 编辑:程序博客网 时间:2024/06/01 10:02
不得不说真是天下文章一大抄,坑真多,费了好大的劲,才成功搞定android 的http请求。
本来想用人家封装好的,发现都有各种错误,okhttp已经更新了,部分函数也变动了,博客没改,git也没改,
想想还是从基础做起,慢慢封装自己的一些公用类吧。
一、准备工作
到官网下载最新版的okhttp.jar
下载地址:http://square.github.io/okhttp/
拷贝到libs文件夹,右键-Add As Library,这时需要稍等10秒钟左右,AS要构建函数库。
添加权限:
<!--连接网络--> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <!--读写文件--> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
下边就能正式使用了。
二、直接上代码
/** * 上传文件及参数 */ private void sendMultipart(){ File sdcache = getExternalCacheDir(); int cacheSize = 10 * 1024 * 1024; //设置超时时间及缓存,下边都应该这样设置的。 OkHttpClient.Builder builder = new OkHttpClient.Builder() .connectTimeout(15, TimeUnit.SECONDS) .writeTimeout(20, TimeUnit.SECONDS) .readTimeout(20, TimeUnit.SECONDS) .cache(new Cache(sdcache.getAbsoluteFile(), cacheSize)); OkHttpClient mOkHttpClient=builder.build(); RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("title", "wangshu")//设置post的参数 .addFormDataPart("image", "wangshu.jpg",//如何接收图片,还在研究 RequestBody.create(MEDIA_TYPE_PNG, new File("/sdcard/wangshu.jpg"))) .build(); Request request = new Request.Builder() .header("Authorization", "Client-ID " + "...") .url("https://***.php")//请求的url .post(requestBody) .build(); mOkHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { Log.i("InfoMSG", response.body().string()); } }); } /** * 异步下载文件 */ private void downAsynFile() { OkHttpClient mOkHttpClient = new OkHttpClient(); String url = "http://***.jpg"; Request request = new Request.Builder().url(url).build(); mOkHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) { InputStream inputStream = response.body().byteStream(); FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(new File("/sdcard/123.jpg")); byte[] buffer = new byte[2048]; int len = 0; while ((len = inputStream.read(buffer)) != -1) { fileOutputStream.write(buffer, 0, len); } fileOutputStream.flush(); } catch (IOException e) { Log.i("InfoMSG", "IOException"); e.printStackTrace(); } Log.d("InfoMSG", "文件下载成功"); } }); } /** * 异步上传文件 */ private void postAsynFile() { OkHttpClient mOkHttpClient=new OkHttpClient(); File file = new File("/sdcard/123.txt"); Request request = new Request.Builder() .url("https://www.****.php") .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file)) .build(); mOkHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { Log.i("InfoMSG",response.body().string()); } }); } private void getAsynHttp() { OkHttpClient mOkHttpClient=new OkHttpClient(); Request.Builder requestBuilder = new Request.Builder().url("http://www.baidu.com"); //可以省略,默认是GET请求 requestBuilder.method("GET",null); Request request = requestBuilder.build(); Call mcall= mOkHttpClient.newCall(request); mcall.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { if (null != response.cacheResponse()) { String str = response.cacheResponse().toString(); Log.i("InfoMSG", "cache---" + str); } else { response.body().string(); String str = response.networkResponse().toString(); Log.i("InfoMSG", "network---" + str); } runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), "请求成功", Toast.LENGTH_SHORT).show(); } }); } }); } /** * 异步http post数据 */ private void postAsynHttp() { OkHttpClient mOkHttpClient = new OkHttpClient(); RequestBody formBody = new FormBody.Builder() .add("tel", "10") .build(); Request request = new Request.Builder() .url("http://192.168.1.105/interface/index.php") .post(formBody) .build(); Call call = mOkHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { String str = response.body().string(); Log.i("InfoMSG", str); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), "请求成功", Toast.LENGTH_SHORT).show(); } }); } }); }<pre name="code" class="java">/** * post JSON 对象 */ private void postJSONObj(){ File sdcache = getExternalCacheDir(); int cacheSize = 10 * 1024 * 1024; //设置超时时间及缓存 OkHttpClient.Builder builder = new OkHttpClient.Builder() .connectTimeout(15, TimeUnit.SECONDS) .writeTimeout(20, TimeUnit.SECONDS) .readTimeout(20, TimeUnit.SECONDS) .cache(new Cache(sdcache.getAbsoluteFile(), cacheSize)); OkHttpClient mOkHttpClient=builder.build(); RequestBody requestBody1=RequestBody.create(JSON,"\"user\":\"abc\""); Request request = new Request.Builder() .url("https://***.php") .post(requestBody1) .build(); mOkHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { Log.i("InfoMSG", response.body().string()); } }); }
三、服务器接收
$_REQUEST["tel"]//接收post的参数$GLOBALS["HTTP_RAW_POST_DATA"]//接收json对象
1、上传图片
$act = $_GET["action"];if ($act == "postimg") {$content = file_get_contents("php://input");$imgName = time();$folder = "images";$file_dir = $folder . "/" . $imgName . ".jpg";try {if (!file_exists($folder)) {//判断目录是否存在mkdir($folder);//创建目录}if ($fp = fopen($file_dir, 'w')) {if (fwrite($fp, $content)) {//写入文件fclose($fp);}}} catch(Exception $ex) {echo "".$ex;}echo "图片上传成功";}
0 0
- Android Studio 网络编程 OkHttp3 用法
- Android网络编程OkHttp3用法全解析
- Android网络编程Okhttp3用法详解
- Android网络编程-OkHttp3用法全解析
- Android网络编程(六)OkHttp3用法全解析
- Android网络编程(六)OkHttp3用法全解析
- Android网络编程(六)OkHttp3用法全解析
- Android网络编程(六)OkHttp3用法全解析
- Android网络编程(六)OkHttp3用法全解析
- Android网络编程(六)OkHttp3用法全解析
- Android之网络编程OkHttp3用法全解析
- Android 网络编程(四)OkHttp3完全解析
- Android-网络框架01OKHttp3
- Android网络请求框架----okHttp3
- android 网络框架之okhttp3
- Android中的OkHttp3简单用法.
- OkHttp3-Android网络请求框架常用用法介绍与实例(mob请求天气预报)
- OkHttp3-Android网络请求框架常用用法介绍与实例(mob请求天气预报),还好!
- 字符实体集合
- 剑指offer--面试题41:和为S的两个数字 vs 和为S的连续正数序列
- Linux C 文件管理2
- javaScript实现弹出层效果
- web.xml is missing and <failOnMissingWebXml> is set to true
- Android Studio 网络编程 OkHttp3 用法
- System.arraycopy()从指定源数组中复制一个数组
- 设置导航栏透明,tableview不能下拉,并默认起点(0,0),页面消失后导航栏还原
- android开发游记:RecycleView 实现复杂首页布局三种方式
- Codeforces Round #373 (Div. 1) C.Sasha and Array
- 编辑器扩展——模板
- Android自定义控件之简介
- 重载函数
- OpenJudge - 2989 糖果 动态规划(DP) 重庆一中高2018级竞赛班第十一次测试 2016.9.24 Problem 2