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());
            }
        });
    }





}

 

posted @ 2016-12-29 15:55  咖喱不见不散啊  阅读(843)  评论(0编辑  收藏  举报