您的位置:首页 > 理论基础 > 计算机网络

Android之okhttp的用法

2017-05-15 21:08 204 查看
概述:

okhttp是一个网络框架,非常厉害的网络框架。要使用okhttp,Android Stuido只需在gradle文件中添加依赖就可以了。代码:

compile 'com.squareup.okhttp3:okhttp:3.4.2'


接下来看使用:

public class MainActivity extends AppCompatActivity {

private OkHttpClient okHttpClient ;
private ImageView imageView ;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView( R.layout.mainactivity);
imageView = (ImageView) findViewById( R.id.img ) ;
okHttpClient = new OkHttpClient() ;
}

/**
* 同步
* @param view
*/
public void executeMathed(View view) {
final Request request = new Request.Builder().url("http://wwww.baidu.com").get().build() ;
new Thread( new Runnable() {
@Override
public void run() {
try {
Response response = okHttpClient.newCall( request ).execute() ;
String str = response.body().string() ;
System.out.println("数据:"+ str );
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}

/**
* 异步
* @param view
*/
public void enquenecMthed(View view) {
final Request request = new Request.Builder().url("http://www.baidu.com").get().build() ;
okHttpClient.newCall( request ).enqueue( new Callback() {
/**
* 失败的时候调用
* @param call
* @param e
*/
@Override
public void onFailure(Call call , IOException e) {
System.out.println("数据请求失败");
}

/**
* 成功的时候调用
* @param call
* @param response
* @throws IOException
*/
@Override
public void onResponse(Call call, Response response) throws IOException {
System.out.println("数据请求成功");
System.out.println("数据:"+ response.body().string());
}
});

}

/**
* get请求
* @param view
*/
public void sendParams(View view) {
final Request request = new Request.Builder()
.url("https://raw.githubusercontent.com/square/okhttp/master/samples/guide/src/main/java/okhttp3/guide/GetExample.java")
.get()
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {

}

@Override
public void onResponse(Call call, Response response) throws IOException {
//response.body().string();这个方法只能被调用一次
String str = response.body().string();
System.out.println("shangyici:"+str);
//下面这句话打印是空的
System.out.println("java:"+response.body().string());
}
});
}

/**
* post请求
* @param view
*/
public void sendParamsPost(View view) {
String urlparams = "http://www.tngou.net/api/lore/list";
//? & 这写符号自给我们加上(不用我们担心)
FormBody formBody = new FormBody.Builder()
.add("page","2")
.add("rows","5")
.build() ;
//创建请求
Request request = new Request.Builder()
.post(formBody)
.url(urlparams)
.build();
okHttpClient.newCall( request ).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}

@Override
public void onResponse(Call call, Response response) throws IOException {
System.out.println( response.body().string());
}
});
}

/**
* 上传文件
* @param view
*/
public void uploadFile(View view) {
//第一步 需要一个文件对象(需要上传的文件)
File file  = new File( Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_DOWNLOADS ),"privatekey.sys" ) ;
//第二步:构建一个Multipartbody对象
MultipartBody.Builder mrb = new MultipartBody.Builder() ;
//设置上传协议格式
mrb.setType( MultipartBody.FORM ) ;
//第三步:创建一个ReqequstBody对象
RequestBody requestBody = RequestBody.create( MediaType.parse( "text/html" ) , file ) ;
//为表单添加数据
mrb.addFormDataPart(
"file" //form表单里面的key值
,"XIAOY"//服务器上保存的名字
,requestBody//设置请求体
);

final Request request = new Request.Builder()
.url("http://10.3.135.81:10000/file/upload")//服务器的IP和端口号
.post( mrb.build() )
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call , IOException e) {
e.printStackTrace() ;
}
@Override
public void onResponse(Call call, Response response) throws IOException {
System.out.println("返回的是服务器文件在服务器上的完整路径:"+ response.body().string() ) ;
}
});
}

/**
* 下载文件
* @param view
*/
public void downloadFile(View view) {
Request request = new Request.Builder()
.url("http://i.ce.cn/ent/news/201610/25/W020161025327194695250.jpg ")
.get()
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {

}
@Override
public void onResponse( Call call , Response response) throws IOException {
final ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
InputStream ins = response.body().byteStream() ;
int len = -1 ;
byte[] bytes = new byte[1024] ;
while ((len=ins.read(bytes)) != -1){
//一次读取多少就写多少
bos.write( bytes , 0 , len ) ;
}
ins.close() ;
runOnUiThread( new Runnable() {
@Override
public void run() {
imageView.setImageBitmap(BitmapFactory.decodeByteArray( bos.toByteArray() , 0 , bos.toByteArray().length ));
Toast.makeText(MainActivity.this,"下载完成",Toast.LENGTH_SHORT).show();
}
});
}
});
}
}

XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<Button
android:onClick="executeMathed"
android:text="OkHttp同步方法"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

<Button
android:onClick="enquenecMthed"
android:text="OkHttp异步方法"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

<Button
android:text="okHttp传递参数"
android:onClick="sendParams"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

<Button
android:text="okHttp传递参数之Post"
android:onClick="sendParamsPost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

<Button
android:text="okHttp上传文件"
android:onClick="uploadFile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

<Button
android:onClick="downloadFile"
android:text="下载文件"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

<ImageView
android:id="@+id/img"
android:layout_width="130sp"
android:layout_height="130dp"/>

</LinearLayout>

这是非常简单的用法,高级用法,本人也不会,以后继续学习了在更新。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: