Android 普通okhttp、okhttp utils执行 post get请求,文件上传下载、请求图片
public class OKHttpActivity extends Activity implements View.OnClickListener {
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
/**
* get请求
*/
private static final int GET = 1;
/**
* post请求
*/
private static final int POST = 2;
private static final String TAG = OKHttpActivity.class.getSimpleName();
private Button btn_get_post;
private TextView tv_result;
private Button btn_get_okhttputils;
private Button btn_downloadfile;
private ProgressBar mProgressBar;
private Button btn_uploadfile;
private Button btn_image;
private Button btn_image_list;
private ImageView iv_icon;
private OkHttpClient client = new OkHttpClient();
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case GET:
//获取数据
tv_result.setText((String) msg.obj);
break;
case POST:
//获取数据
tv_result.setText((String) msg.obj);
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_okhttp);
btn_get_post = (Button) findViewById(R.id.btn_get_post);
tv_result = (TextView) findViewById(R.id.tv_result);
btn_get_okhttputils = (Button) findViewById(R.id.btn_get_okhttputils);
btn_downloadfile = (Button) findViewById(R.id.btn_downloadfile);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
btn_uploadfile = (Button) findViewById(R.id.btn_uploadfile);
iv_icon = (ImageView) findViewById(R.id.iv_icon);
btn_image = (Button) findViewById(R.id.btn_image);
btn_image_list = (Button) findViewById(R.id.btn_image_list);
//设置点击事件
btn_get_post.setOnClickListener(this);
btn_get_okhttputils.setOnClickListener(this);
btn_downloadfile.setOnClickListener(this);
btn_uploadfile.setOnClickListener(this);
btn_image.setOnClickListener(this);
btn_image_list.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_get_post://使用原生的okhttp请求网络数据,get和post
tv_result.setText("");
getDataFromPost();//点击事件
break;
case R.id.btn_get_okhttputils:
// getDataGetByOkhttpUtils();
getDataPostByOkhttpUtils();
break;
case R.id.btn_downloadfile://下载文件
downloadFile();
break;
case R.id.btn_uploadfile://文件上传
multiFileUpload();
break;
case R.id.btn_image://请求单张图片
getImage();
break;
case R.id.btn_image_list://请求列表中的图片
Intent intent = new Intent(OKHttpActivity.this,OKHttpListActivity.class);
startActivity(intent);
break;
}
}
/**
* 使用get请求网络数据
*/
private void getDataFromGet() {
new Thread() {
@Override
public void run() {
super.run();
try {
String result = get("http://api.m.mtime.cn/PageSubArea/TrailerList.api");
Log.e("TAG", result);
Message msg = Message.obtain();
msg.what = GET;
msg.obj = result;
handler.sendMessage(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
/**
* 使用post请求网络数据
*/
private void getDataFromPost() {
new Thread() {
@Override
public void run() {
super.run();
try {
String result = post("http://api.m.mtime.cn/PageSubArea/TrailerList.api", "");
Log.e("TAG", result);
Message msg = Message.obtain();
msg.what = POST;
msg.obj = result;
handler.sendMessage(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
/**
* get请求
*
* @param url 网络连接
* @return
* @throws IOException
*/
private String get(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
/**
* okhttp3的post请求
*
* @param url
* @param json
* @return
* @throws IOException
*/
private String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
/**
* 使用okhttp-utils的get请求网络文本数据
*/
public void getDataGetByOkhttpUtils() {
String url = "http://www.zhiyun-tech.com/App/Rider-M/changelog-zh.txt";
// url="http://www.391k.com/api/xapi.ashx/info.json?key=bd_hyrzjjfb4modhj&size=10&page=1";
url = "http://api.m.mtime.cn/PageSubArea/TrailerList.api";
OkHttpUtils
.get()
.url(url)
.id(100)
.build()
.execute(new MyStringCallback());
}
/**
* 使用okhttp-utils的post请求网络文本数据
*/
public void getDataPostByOkhttpUtils() {
String url = "http://www.zhiyun-tech.com/App/Rider-M/changelog-zh.txt";
// url="http://www.391k.com/api/xapi.ashx/info.json?key=bd_hyrzjjfb4modhj&size=10&page=1";
url = "http://api.m.mtime.cn/PageSubArea/TrailerList.api";
OkHttpUtils
.post()
.url(url)
.id(100)
.build()
.execute(new MyStringCallback());
}
public class MyStringCallback extends StringCallback {
@Override
public void onBefore(Request request, int id) {
setTitle("loading...");
}
@Override
public void onAfter(int id) {
setTitle("Sample-okHttp");
}
@Override
public void onError(Call call, Exception e, int id) {
e.printStackTrace();
tv_result.setText("onError:" + e.getMessage());
}
@Override
public void onResponse(String response, int id) {
Log.e(TAG, "onResponse:complete");
tv_result.setText("onResponse:" + response);
switch (id) {
case 100:
Toast.makeText(OKHttpActivity.this, "http", Toast.LENGTH_SHORT).show();
break;
case 101:
Toast.makeText(OKHttpActivity.this, "https", Toast.LENGTH_SHORT).show();
break;
}
}
@Override
public void inProgress(float progress, long total, int id) {
Log.e(TAG, "inProgress:" + progress);
mProgressBar.setProgress((int) (100 * progress));
}
}
/**
* 使用okhttp-utils下载大文件
*/
public void downloadFile()
{
String url = "http://vfx.mtime.cn/Video/2016/07/24/mp4/160724055620533327_480.mp4";
OkHttpUtils//
.get()//
.url(url)//
.build()//
.execute(new FileCallBack(Environment.getExternalStorageDirectory().getAbsolutePath(), "okhttp-utils-test.mp4")//
{
@Override
public void onBefore(Request request, int id)
{
}
@Override
public void inProgress(float progress, long total, int id)
{
mProgressBar.setProgress((int) (100 * progress));
Log.e(TAG, "inProgress :" + (int) (100 * progress));
}
@Override
public void onError(Call call, Exception e, int id)
{
Log.e(TAG, "onError :" + e.getMessage());
}
@Override
public void onResponse(File file, int id)
{
Log.e(TAG, "onResponse :" + file.getAbsolutePath());
}
});
}
/**
* 使用okhttp-utils上传多个或者单个文件
*/
public void multiFileUpload()
{
String mBaseUrl = "http://192.168.0.165:8080/FileUpload/FileUploadServlet";
File file = new File(Environment.getExternalStorageDirectory(), "afu.png");
File file2 = new File(Environment.getExternalStorageDirectory(), "test.txt");
if (!file.exists()||!file2.exists())
{
Toast.makeText(OKHttpActivity.this, "文件不存在,请修改文件路径", Toast.LENGTH_SHORT).show();
return;
}
Map<String, String> params = new HashMap<>();
params.put("username", "杨光福");
params.put("password", "123");
String url = mBaseUrl ;
OkHttpUtils.post()//
.addFile("mFile", "server_afu.png", file)//
.addFile("mFile", "server_test.txt", file2)//
.url(url)
.params(params)//
.build()//
.execute(new MyStringCallback());
}
public void getImage()
{
tv_result.setText("");
String url = "http://images.csdn.net/20150817/1.jpg";
OkHttpUtils
.get()//
.url(url)//
.tag(this)//
.build()//
.connTimeOut(20000)
.readTimeOut(20000)
.writeTimeOut(20000)
.execute(new BitmapCallback() {
@Override
public void onError(Call call, Exception e, int id) {
tv_result.setText("onError:" + e.getMessage());
}
@Override
public void onResponse(Bitmap bitmap, int id) {
Log.e("TAG", "onResponse:complete");
iv_icon.setImageBitmap(bitmap);
}
});
}
}
Android 普通okhttp、okhttp utils执行 post get请求,文件上传下载、请求图片的更多相关文章
- Android okHttp网络请求之文件上传下载
前言: 前面介绍了基于okHttp的get.post基本使用(http://www.cnblogs.com/whoislcj/p/5526431.html),今天来实现一下基于okHttp的文件上传. ...
- SSM + Android 网络文件上传下载
SSM + Android 网络交互的那些事 2016年12月14日 17:58:36 ssm做为后台与android交互,相信只要是了解过的人都知道一些基本的数据交互,向json,对象,map的交互 ...
- 批量执行(Linux命令,上传/下载文件)
前言: 每个公司的网络环境大都划分 办公网络.线上网络,之所以划分的主要原因是为了保证线上操作安全: 对于外部用户而言也只能访问线上网络的特定开放端口,那么是什么控制了用户访问线上网络的呢? 防火墙过 ...
- Python Paramiko实现sftp文件上传下载以及远程执行命令
一.简介 Paramiko模块是基于Python实现的SSH远程安全连接,用于SSH远程执行命令.文件传输等功能. 安装模块 默认Python没有自带,需要手动安装: pip3 install par ...
- Android与Asp.Net Web服务器的文件上传下载BUG汇总[更新]
遇到的问题: 1.java.io.IOException: open failed: EINVAL (Invalid argument)异常,在模拟器中的sd卡创建文件夹和文件时报错 出错原因可能是: ...
- Android 开发工具类 32_通过 HTTP 协议实现文件上传
完成像带有文件的用户数据表单的上传,而且可以上传多个文件,这在用户注册并拍照时尤其有用. import java.io.BufferedReader; import java.io.ByteArray ...
- OkHttp 优雅封装 HttpUtils 之 上传下载解密
曾经在代码里放荡不羁,如今在博文中日夜兼行,只为今天与你分享成果.如果觉得本文有用,记得关注我,我将带给你更多. 还没看过第一篇文章的欢迎移步:OkHttp 优雅封装 HttpUtils 之气海雪山初 ...
- RxHttp 完美适配Android 10/11 上传/下载/进度监听
1.前言 随着Android 11的正式发布,适配Android 10/11 分区存储就更加的迫切了,因为Android 11开始,将强制开启分区存储,我们就无法再以绝对路径的方式去读写非沙盒目录下的 ...
- android批量文件上传(android批量图片上传)
项目中多处用到文件批量上传功能,今天正好解决了此问题,在此写出来,以便日后借鉴. 首先,以下架构下的批量文件上传可能会失败或者不会成功: 1.android客户端+springMVC服务端:服务端 ...
随机推荐
- sublime的markdown插件
mac安装 shift+command+p调出package control面板,搜索install调查安装软件搜索面板 搜索需要安装markdown软件 我安装了下面两个:MarkdownLiveP ...
- 由内省引出JavaBean的应用
IntroSpector-->javaBean-->特殊的java类 get和set方法 ReflectPoint pt1 = new ReflectPoint(3,5); String ...
- JavaScript中给二维数组动态添加元素的质朴方法
var myData = new Array(); for(var i=0;i<tableDatas.length;i++){ var arr=tableDatas[i]; ...... /// ...
- HDU 1017 A Mathematical Curiosity (枚举水题)
Problem Description Given two integers n and m, count the number of pairs of integers (a,b) such tha ...
- hdu2955 Robberies (01背包)
转载请注明出处:http://blog.csdn.net/u012860063 题目链接:pid=2955">http://acm.hdu.edu.cn/showproblem.php ...
- sql server 数据库系统整理——数据表的创建和管理
注意: 1. 固定长度字符类型比非固定长度字符类型占用空间要大,可是因为进行字段值设置的时候固定长度字符类型无需进行长度处理就能够进行,因此它的处理速度更快. 所以 对于长度相对固 ...
- Vue 响应式属性
本文参考自:https://www.w3cplus.com/vue/vue-reactivity-and-pitfalls.html 1.概述 当创建一个Vue实例时,每个数据属性.组件属性等都是可以 ...
- Ubuntu下安装JDK图文解析
我们在64位的Ubuntu中安装JDK,选择的是jdk1.6.0_32版本号.安装文件名称为jdk-6u32-linux-x64.bin(这个是64位系统的),假设是32位系统的还须要去官网下载32位 ...
- bootstrap selectpicker使用问题
文档查阅:http://silviomoreto.github.io/bootstrap-select/options/ 1.实用属性 size:5 表示下拉列表默认展示5行(ie8展示4.5行) ...
- linux 挂载相关
mount命令的用法,以及技巧光盘镜像文件.移动硬盘.共享文件夹及U盘的方法. 一,挂接命令(mount) 挂接(mount)命令的使用方法. 命令格式: mount [-t vfstype] [- ...