转载请注意:http://blog.youkuaiyun.com/wjzj000/article/details/53711200
本菜开源的一个自己写的Demo,希望能给Androider们有所帮助,水平有限,见谅见谅…
https://github.com/zhiaixinyang/PersonalCollect (拆解GitHub上的优秀框架于一体,全部拆离不含任何额外的库导入)
https://github.com/zhiaixinyang/MyFirstApp(Retrofit+RxJava+MVP)
本篇博客继续记录OkHttp的用法
如果有兴趣可以返回阅读本系列的上部分:http://blog.youkuaiyun.com/wjzj000/article/details/53677706
服务器绑定了域名
因此以前URL前面部分:http://120.27.4.196:8080/
需要更换成http://www.ohonor.xyz/
上篇是关于GET方法的使用,那么这次就到了POST。
不过因为服务器暂时只写了处理表单的程序。所以今天先记录:
POST form Parameters
//这里使用的是OkHttp3.5版本,所以这里和2.x的版本有区别。请往下看。
okHttpClient=new OkHttpClient();
/**
* 这里需要使用FormBody的构建者模式进行构建请求体。
* 这是add方法所传入的key,是和后台协商决定的,也就是固定写法。
*/
RequestBody requestBody=new FormBody.Builder()
.add("username",etUserName.getText().toString())
.add("password",etPassWord.getText().toString())
.build();
request=new Request.Builder()
.url(path)
//使用post方法,并传入请求体
.post(requestBody)
.build();
call=okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {}
@Override
public void onResponse(Call call, final Response response) throws IOException {
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
tvContent.setText(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
});
我们在正常使用表单方式传数据时,OkHttp3.x版本之前会用到FormEncodingBuilder这个类去进行相关操作。而OkHttp3之后,用FormBody进行了取代,也就是上述代码。
还有一些不同,将随着不断的深入逐步加入。
加载图片(从服务器下载并加载)
private String imagePath="http://120.27.4.196:8080/image/TestImage.png";
request=new Request.Builder()
.url(imagePath)
.build();
call=okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, final IOException e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
tvContent.setText(e.getMessage());
}
});
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
//获取输出流,然后通过BitmapFactory生成Bitmap
InputStream is=response.body().byteStream();
final Bitmap bitmap=BitmapFactory.decodeStream(is);
runOnUiThread(new Runnable() {
@Override
public void run() {
tvContent.setText("加载成功。");
imageView.setImageBitmap(bitmap);
}
});
}
});
效果如下
POST String类型(JSON格式)
服务器URL:private String postStringPath=”http://101.200.56.5:8080/strutstest/postString”;
//自己写的javabean类。
AccountBean accountBean=new AccountBean();
accountBean.setUsername(etUserName.getText().toString());
accountBean.setPassword(etPassWord.getText().toString());
request=new Request.Builder()
.url(postStringPath)
//通过RequestBoby构建发送的数据。MediaType用于表名传递数据的类型
//什么样的数据对应什么样的MediaType的第一个参数。百度MIME...
.post(RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"),new Gson().toJson(accountBean)))
.build();
call=okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
TestActivity.this.string = response.body().string();
TestActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
tvContent.setText(string);
}
});
}
});
POST上传图片至服务器
服务器URL:private String postImagePath=”http://101.200.56.5:8080/strutstest/fileUpload”;
//imagePath的获取见下文
File file=new File(imagePath);
request=new Request.Builder()
.url(postImagePath)
.post(RequestBody.create(MediaType.parse("text/x-markdown; charset=utf-8"),file))
.build();
call=okHttpClient.newCall(request);
call.enqueue(new Callback() {
//省略
}
//代码中涉及的方法见下边。
public void openImage(View view){
Intent openImage=new Intent(Intent.ACTION_PICK,null);
openImage.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*");
startActivityForResult(openImage, 6566);
}
Bitmap bmp;
String imagePath;
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode== Activity.RESULT_OK&&requestCode==6566){
if (data!=null){
Uri selectImageUri=data.getData();
imagePath = FileUtils.getPathUrlFromUri(this,selectImageUri);
bmp= FileUtils.getBitmap(imagePath);
imageView.setImageBitmap(bmp);
}
}
}
//通过uri获取图片的绝对url
public static String getPathUrlFromUri(Context context, android.net.Uri uri){
if ( null == uri ) return null;
final String scheme = uri.getScheme();
String data = null;
if ( scheme == null )
data = uri.getPath();
else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) {
data = uri.getPath();
} else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) {
Cursor cursor = context.getContentResolver().query( uri, new String[] { MediaStore.Images.ImageColumns.DATA }, null, null, null );
if ( null != cursor ) {
if ( cursor.moveToFirst() ) {
int index = cursor.getColumnIndex( MediaStore.Images.ImageColumns.DATA );
if ( index > -1 ) {
data = cursor.getString( index );
}
}
cursor.close();
}
}
return data;
}
//通过url获取到Bitmap对象
public static Bitmap getBitmap(String path) {
Bitmap bm = null;
InputStream is = null;
try {
File outFilePath = new File(path);
//判断如果当前的文件不存在时,创建该文件一般不会不存在
if (!outFilePath.exists()) {
boolean flag = false;
try {
flag = outFilePath.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("---创建文件结果----" + flag);
}
is = new FileInputStream(outFilePath);
bm = BitmapFactory.decodeStream(is);
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return bm;
}
如果我们使用AS自带的虚拟机,怎么上传图片到虚拟机中呢?
找到ADM就好了。我是AS2.2的版本,ADM的位置如下:
整体效果如下:
PS:相关源码基本都存放于我的这个开源项目之中:
https://github.com/zhiaixinyang/PersonalCollect
尾声
OK,关于OkHttp的各种用法,就介绍到这了。说实话比较简单。如果有不懂的,可以看一看官方文档https://github.com/square/okhttp/wiki/Recipes或是其他大神们的见解。祝大家早日出任CEO,赢取白富美,走上人生巅峰!!
最后希望各位看官可以star我的GitHub,三叩九拜,满地打滚求star:
https://github.com/zhiaixinyang/PersonalCollect
https://github.com/zhiaixinyang/MyFirstApp