zoukankan      html  css  js  c++  java
  • Okhttp3的简单使用

    1.get请求:

    /**
     *
     *okhttp get请求
     * */
    public class MainActivity extends AppCompatActivity {
    
        private static final String TAG = "MainActivity";
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            /**
             * 创建okhttpClient对象
             * */
            OkHttpClient mOkHttpClient = new OkHttpClient();
            /**
             *创建Request对象
             **/
            final Request request = new Request.Builder()
                    .url("http://v.juhe.cn/toutiao/index?type=top&key=3f8238bb55566d2b3f0d2204a5e9631f")
                    .build();
            /**
             * new Call
             * */
            Call call = mOkHttpClient.newCall(request);
    
            /**
             * 请求调度
             * */
            call.enqueue(new Callback()
            {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e(TAG, "onFailure: "+e.toString());
                }
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String htmlStr =  response.body().string();
                    Log.d(TAG, "onResponse() called with: " + "call = [" + call + "], response = [" + htmlStr + "]");
                }
            });
        }
    }

    2,post请求:

    /**
     *
     * okhttp  post请求
     * */
    public class MainActivity extends AppCompatActivity {
    
        private static final String TAG = "MainActivity";
        /**
         * 请求地址
         * */
        String URL = "这里为请求地址";
        JSONObject obj = new JSONObject();
        String sss;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            /**
             * post请求体为json字符串
             * */
            try {
                obj.put("name", "123");
                obj.put("pwd", "456");
                sss = obj.toString();
                post(URL, sss);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
       public void post(String url, String json) throws IOException {
            OkHttpClient client = new OkHttpClient();
            MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            RequestBody body = RequestBody.create(JSON, json);
            Request request = new Request.Builder().url(url).post(body).build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e(TAG, "onFailure: "+e.toString() );
                }
    
                @Override
                public void onResponse(Call call, Response response) throws IOException {
    
                    Log.i(TAG, "onResponse*: "+response.body().string());
                }
            });
    
            
        }
    }

     3.okhttp下载文件

        <uses-permission android:name="android.permission.INTERNET"/>
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    /**
     *okhttp 下载文件
     *
     * */
    public class MainActivity extends AppCompatActivity {
    
        private static final String TAG = "MainActivity";
        OkHttpClient mOkHttpClient=new OkHttpClient();
        /**
         * 请求地址
         * */
        String LOAD1="http://gdown.baidu.com/data/wisegame/baidusearch_Android_10189_1399k.apk" ;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Request request = new Request.Builder().url(LOAD1).build();
            mOkHttpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e(TAG, "onFailure: "+e.toString() );
                }
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    InputStream is = null;
                    byte[] buf = new byte[2048];
                    int len = 0;
                    FileOutputStream fos = null;
                    String SDPath = Environment.getExternalStorageDirectory().getAbsolutePath();
                    try {
                        is = response.body().byteStream();
                        File file = new File(SDPath, "test.apk");
                        fos = new FileOutputStream(file);
                        while ((len = is.read(buf)) != -1) {
                            fos.write(buf, 0, len);
                        }
                        fos.flush();
                        Log.d(TAG, "文件下载成功");
                    } catch (Exception e) {
                        Log.d(TAG, "文件下载失败"+e.toString());
                    } finally {
                        try {
                            if (is != null)
                                is.close();
                        } catch (IOException e) {
                        }
                        try {
                            if (fos != null)
                                fos.close();
                        } catch (IOException e) {
                        }
                    }
                }
            });
        }
    
    
    
    
    
    }

    4. okhttp上传文件

    /**
     *okhttp 上传文件
     *
     * */
    public class MainActivity extends AppCompatActivity {
    
        private static final String TAG = "MainActivity";
    
        /**
         * 请求地址
         * */
        String LOAD1="http://192.168.2.104:8080/Gaccept/u/test" ;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            String SDPath = Environment.getExternalStorageDirectory().getAbsolutePath();
            File file = new File(SDPath, "test.apk");
            RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
            RequestBody requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("myfile", "test.apk", fileBody)
                    .build();
            Request request = new Request.Builder()
                    .url(LOAD1)
                    .post(requestBody)
                    .build();
    
    
            final okhttp3.OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder();
            OkHttpClient okHttpClient  = httpBuilder
                    /**
                     * 设置超时
                     * */
                    .connectTimeout(10, TimeUnit.SECONDS)
                    .writeTimeout(15, TimeUnit.SECONDS)
                    .build();
            okHttpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e(TAG, "uploadMultiFile()11 e=" + e);
                }
    
    
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    Log.i(TAG, "uploadMultiFile() response11=" + response.body().string());
                }
            });
        }
    
    
    
    
    
    }
    今天多一点积累,明天少一分烦恼
  • 相关阅读:
    1111---9999的变换
    Mac命令行
    iOS 支付 [支付宝、银联、微信]
    ShareSDK适配iOS 9系统
    iOS中Size Classes的理解与使用
    iOS9网络请求升级 之前的不显示图片 破解方法
    iOS9中友盟分享不能使用 破解方法
    iOS9中错误信息信息是引入的一个第三方库不包含bitcode
    iOS 六大手势
    下拉刷新和上拉加载的原理
  • 原文地址:https://www.cnblogs.com/galibujianbusana/p/6233416.html
Copyright © 2011-2022 走看看