OkHttpClient GET与POST请求

来源:互联网 发布:手机淘宝 无响应 编辑:程序博客网 时间:2024/06/10 03:32

先导下依赖
  compile 'com.squareup.okhttp3:okhttp:3.6.0'    compile 'com.squareup.okio:okio:1.11.0'
dependencies {    compile fileTree(dir: 'libs', include: ['*.jar'])    compile 'com.squareup.okhttp3:okhttp:3.6.0'    compile 'com.squareup.okio:okio:1.11.0'    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {        exclude group: 'com.android.support', module: 'support-annotations'    })


public class MainActivity extends AppCompatActivity {



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);




    }


    /**
     * Caused by: android.os.NetworkOnMainThreadException
     *
     * 同步GET的意思是一直等待http请求, 直到返回了响应. 在这之间会阻塞进程,
     * 所以通过get不能在Android的主线程中执行, 否则会报错
     * @param view
     */
    public void getTongBu(View view) {


        new Thread(){
            @Override
            public void run() {
                //1.创建一个okhttp客户端对象
                OkHttpClient okHttpClient = new OkHttpClient();


                //2.创建一个请求的对象....默认就是get方式
                Request request = new Request.Builder()
                        .url("https://www.zhaoapi.cn/ad/getAd")
                        .build();
                //3.客户端要去调用一个请求的对象
                Call call = okHttpClient.newCall(request);


                //4.执行....指定同步还是异步请求的方式....call.execute()同步的方式
                try {
                    Response response = call.execute();


                    if (response.isSuccessful()){


                        /**
                         * * 响应体的 string() 方法对于小文档来说十分方便、高效。但是如果响应体太大(超过1MB),
                         * 应避免适应 string()方法 ,因为他会将把整个文档加载到内存中。
                         * 对于超过1MB的响应body,应使用流的方式来处理body。
                         */
                        Log.i("------",response.body().string());


                        //设置适配器....handler...runOnUiThread()


                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();






    }


    public void getYiBu(View view) {


        OkHttpClient okHttpClient = new OkHttpClient();


        final Request request = new Request.Builder()
                .url("https://www.zhaoapi.cn/ad/getAd")
                .build();


        Call call = okHttpClient.newCall(request);


        //指定call调用的方式
        call.enqueue(new Callback() {
            //失败
            @Override
            public void onFailure(Call call, IOException e) {
                //打印异常的日志
                e.printStackTrace();
            }


            //服务器有响应....这个位置仍然是工作线程
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()){


                    //response.body().string();


                    //java.lang.IllegalStateException: closed 非法状态异常:关闭...本次请求已经响应,,,关闭
                    Log.i("------",response.body().string());


                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this,"请求成功",Toast.LENGTH_SHORT).show();
                        }
                    });


                }
            }
        });


    }


    /**
     * post和get都有同步和异步的方式.....区别就在于call调用的方法不同
     * @param view
     */
    public void postYiBu(View view) {


        OkHttpClient okHttpClient = new OkHttpClient();


        //2.传递参数使用FormBody请求实体对象
        FormBody formBody = new FormBody.Builder()
                .add("mobile", "15715317583")
                .add("password", "123456")
                .build();


        //3.获取post方式的请求对象
        Request request = new Request.Builder()
                .post(formBody)
                .url("https://www.zhaoapi.cn/user/reg")
                .build();
        //4.
        Call call = okHttpClient.newCall(request);


        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }


            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                if (response.isSuccessful()){


                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Toast.makeText(MainActivity.this,response.body().string(),Toast.LENGTH_SHORT).show();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
            }
        });


    }


    /**
     * java.io.FileNotFoundException: /storage/emulated/0/note01.md: open failed: EACCES (Permission denied)
     * 文件未找到的异常....打开失败了....权限拒绝
     *
     * 6.0以后权限是运行时权限...
     * ------------1.把targetSdk版本改到23以下
     * ------------2.http://www.jianshu.com/p/a51593817825 使用运行时权限
     *
     * 图片:改变文件的类型,,,,在换掉一个支持图片上传的地址
     *
     * 多张图片.....循环上传
     *
     * @param view
     */
    public void postShangChuan(View view) {

弹出框 支持sdk6.0以上 手机也是
        //A.检查用户是否已经允许了权限....PackageManager.PERMISSION_GRANTED代表的是用户已经允许


        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            //B.不允许...的时候,,,请求用户允许这个权限
            // Activity arg0代表当前的activity, @NonNull String[] arg1请求的权限的数组,也就是需要请求允许哪些权限, int arg2请求码
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1001);


        }else {
            //允许...上传文件
            postFile();

        }

 private void postFile() {
        //1.
        OkHttpClient okHttpClient = new OkHttpClient();


        //2.指定文件的类型 image/jpg image/png video/mp4 ...mimeType
        MediaType mediaType = MediaType.parse("text/x-markdown;charset=utf-8");
        //3.指定要上传的文件对象
        File file = new File(Environment.getExternalStorageDirectory(),"note01.md");


        Request request = new Request.Builder()
                //上传文件的时候请求体使用RequestBody.create()获取okhttp3.MediaType contentType 文件的类型,@NotNull java.io.File file上传的文件对象
                .post(RequestBody.create(mediaType, file))
                .url("https://api.github.com/markdown/raw")
                .build();


        //4.
        Call call = okHttpClient.newCall(request);


        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }


            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                if (response.isSuccessful()){


                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Toast.makeText(MainActivity.this,response.body().string(),Toast.LENGTH_SHORT).show();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
            }
        });
    }*/


上传头像----------------------------

    if (requestCode==222&&resultCode== Activity.RESULT_OK){           Bitmap data1 = data.getParcelableExtra("data");            imag.setImageBitmap(data1);        }else if(requestCode==111&&resultCode== Activity.RESULT_OK){//            相册中获取图片            Uri data1 = data.getData();//            工具类            String realFilePath = ImageUtil.getRealFilePath(this, data1);            File file=new File(realFilePath);            imag.setImageURI(data1);            getOkhttp(file);//            自己写的装换路劲           /* String[] proj = { MediaStore.Images.Media.DATA };            Cursor actualimagecursor = managedQuery(data1,proj,null,null,null);            int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);            actualimagecursor.moveToFirst();            String img_path = actualimagecursor.getString(actual_image_column_index);            File file = new File(img_path);//            Uri uri = Uri.fromFile(file);  //将file类型转成uri            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1001);            }else {                //允许...上传文件                imag.setImageURI(data1);                getOkhttp(file);                LogUtils.d("TAG",file.getPath()+"kk--");            }*/        }    }public void getOkhttp(File file){    OkHttpClient okHttpClient = new OkHttpClient();    MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);    //3.指定要上传的文件对象//        File file = new File(Environment.getExternalStorageDirectory(),"fruit8.jpg");//        Log.i("jiaaa","===="+file.getPath());    //参数名,,,参数,,,参数类型,,,路径               上传图片不能太大 是jpg 头像的图片后缀    builder.addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("image/gif"), file));    MultipartBody requestBody = builder.build();    Request request = new Request.Builder()            .post(requestBody)//请求体            .url("https://www.zhaoapi.cn/file/upload?uid=4434&file="+file.getPath())//指定路径            .build();//启动    Call call = okHttpClient.newCall(request);    call.enqueue(new Callback() {        @Override        public void onFailure(Call call, IOException e) {            e.printStackTrace();        }        @Override        public void onResponse(Call call, final Response response) throws IOException {            if (response.isSuccessful()){                final String string = response.body().string();                runOnUiThread(new Runnable() {                    @Override                    public void run() {                        LogUtils.d("TAG",string+"ee--");                    }                });            }        }    });


原创粉丝点击