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

OkHttp网络请求

2017-03-24 14:32 169 查看
   一.在module的build.gradle添加依赖

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

   二.设置布局

  

 <?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    
xmlns:tools="http://schemas.android.com/tools"
    
android:layout_width="match_parent"
    
android:layout_height="match_parent"
    
android:paddingBottom="@dimen/activity_vertical_margin"
    
android:paddingLeft="@dimen/activity_horizontal_margin"
    
android:paddingRight="@dimen/activity_horizontal_margin"
    
android:paddingTop="@dimen/activity_vertical_margin"
    
tools:context="com.zhiyuan3g.myokhttp.MainActivity">

     <Button
        
android:layout_width="wrap_content"
        
android:layout_height="wrap_content"
        
android:text="获取"
        
android:id="@+id/button"
        
android:layout_marginTop="26dp"
        
android:layout_alignParentTop="true"
        
android:layout_alignLeft="@+id/button2"
        
android:layout_alignStart="@+id/button2" />

     <Button
        
android:layout_width="wrap_content"
        
android:layout_height="wrap_content"
        
android:text="发送"
        
android:id="@+id/button2"
        
android:layout_marginTop="32dp"
        
android:layout_below="@+id/button"
        
android:layout_centerHorizontal="true" />

     <ImageView
        
android:layout_width="wrap_content"
        
android:layout_height="wrap_content"
        
android:id="@+id/imageView"
        
android:layout_centerVertical="true"
        
android:layout_centerHorizontal="true" />

   
 </RelativeLayout>

  三.进行OkHttp网络请求

   使用get请求方式

 //实例化OkHttpClient对象
 OkHttpClient okHttpClient=new OkHttpClient();
 //设置请求方式,网址,参数等等。最后构建
 Request requestGet=new Request.Builder()

         //设置请求方式,默认为GET(不写的话)
         //可用method方法设置请求方式,也可以使用get()方法直接指定为GET方式
         .method("GET",null)

         .url("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&" +

                 "sec=1490930679&di=7cd4ea747dbc49fe4766fbbc2d3a78fd&imgtype=j" +

                 "pg&er=1&src=http%3A%2F   %2Fcore1.staticworld.net%2Fimages%2Farticle%2F2014%2F09%2Fgithub-100412130-orig.jpg")

         .build();
 //实例化Call对象
 Call call=okHttpClient.newCall(requestGet);
 //发送异步Get请求,execute为同步方式,enqueue为异步方式
 call.enqueue(new Callback() {

     //请求失败时要做的事
    
@Override
    
public void onFailure(Call call, IOException e) {

         //更新UI线程的另一种方法
         runOnUiThread(new Runnable() {

             @Override
            
public void run() {

                 Toast.makeText(MainActivity.this,"请求失败",Toast.LENGTH_LONG).show();

             }

         });

     }

     //请求成功时要做的事
    
@Override
    
public void onResponse(Call call, Response response) throws IOException {

         //请求完成后还是在子线程中,需要手动更新UI
         //请求的内容在body正文中
         //加载图片代码
         InputStream inputStream=response.body().byteStream();

         Bitmap bitmap= BitmapFactory.decodeStream(inputStream);

         Message msg=Message.obtain();

         msg.obj=bitmap;

         msg.what=0;

         handler.sendMessage(msg);

     }
 });

     使用post请求方式

 //请求正文,方请求参数的地方
 RequestBody body= new FormBody.Builder()

         //加入键值对
         .add("league","%E8%8B%B1%E8%B6%85")

         .add("key","7121c58a9280b7d98ca041949fd579f2")

         .build();

 Request requestPost=new Request.Builder()

         .url("http://op.juhe.cn/onebox/football/league")

         //需要存放正文,post方法比get方法安全性好
         //post方法把网址与用户名和密码分开,用户名和密码被隐藏起来了
         .post(body)

         .build();

 Call callPost=okHttpClient2.newCall(requestPost);

 callPost.enqueue(new Callback() {

     @Override
    
public void onFailure(Call call, IOException e) {

     }

     @Override
    
public void onResponse(Call call, Response response) throws IOException {

         String content=response.body().string();

         Message msg=Message.obtain();

         msg.obj=content;

         msg.what=1;

         handler.sendMessage(msg);

     }
 });

   四.下面是在主线程中自定义Handler类,用来接收子线程传过来的数据

  
private Handler handler=new Handler(){

     @Override
    
public void handleMessage(Message msg) {

         if(msg.what==0){

             image.setImageBitmap((Bitmap) msg.obj);

         }else if(msg.what==1){

             Toast.makeText(MainActivity.this,(String)msg.obj,Toast.LENGTH_LONG).show();

         }

     }

 };

   
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  okhttp网路请求