OkHttp和HttpUrlConnection的示例

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zxwd2015/article/details/60469996

okhttp

//okhttp 使用
    private void textOkHttp() {
        //缓存
        Cache cache = new Cache(getExternalCacheDir(), 1024 * 1024);
        //拦截器
        Interceptor interceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                //拦截 请求和响应
                Request request = chain.request();
                //进行 请求并获取 响应
                Response response = chain.proceed(request);
                return response;
            }
        };
        //OkHttp会自动重试未验证的请求。
        // 当响应是401 Not Authorized时,Authenticator会被要求提供证书。
        // Authenticator的实现中需要建立一个新的包含证书的请求。
        // 如果没有证书可用,返回null来跳过尝试。
        okhttp3.Authenticator authenticator = new okhttp3.Authenticator() {

            @Override
            public Request authenticate(Route route, Response response)
                    throws IOException {
                String credential = Credentials.basic("用户名", "密码");
                return response.request().newBuilder()
                        .header("Authorization", credential)
                        .build();
            }
        };
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .readTimeout(30000, TimeUnit.MILLISECONDS)
                .cache(cache)
                .addInterceptor(interceptor)
                .authenticator(authenticator)
                .build();

        //get请求
        Request request = new Request.Builder()
                .url("接口")
                .addHeader("", "")
                .build();
        try {
            //同步请求
            Response response = okHttpClient.newCall(request).execute();
            response.body().toString();
            //异步请求
            okHttpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

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

                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
        //post请求
//        RequestBody的数据格式都要指定Content-Type,常见的有三种:
//        application/x-www-form-urlencoded 数据是个普通表单
//        multipart/form-data 数据里有文件
//        application/json 数据是个json
        MediaType.parse("application/x-www-form-urlencoded");
        MediaType.parse("multipart/form-data");
        MediaType.parse("application/json");
        //如果数据是表单
        RequestBody body = new FormBody.Builder()
                .add("键", "值")
                .add("键", "值")
                .build();
        //如果数据是个json
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody body1 = RequestBody.create(JSON, "你的json");
        //如果数据包含文件
        RequestBody body2 = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", file.getName(),
                        RequestBody.create(MediaType.parse("image/png"), file))
                .build();
        Request request1 = new Request.Builder()
                .url("")
                .post(body)
                .build();
        try {
            //同步 请求
            okHttpClient.newCall(request).execute();
            //异步 请求
            okHttpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, Response response)
                        throws IOException {
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

httpUrlConnection

//httpurlconnection使用
    //outputStr参数
    private void textHttpUrl(String path, String outputStr) {
        try {
            URL url = new URL(path);
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setDoInput(true);
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setUseCaches(false);
            httpUrlConn.setRequestMethod("get");
            //建立连接,判断状态码
            httpUrlConn.connect();
            if (httpUrlConn.getResponseCode() == 200) {
                // 有数据需要提交
                toRequest(httpUrlConn.getOutputStream(), outputStr);
                //收到返回 的数据
                String responseData = getResponse(httpUrlConn.getInputStream());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void toRequest(OutputStream outputStream, String outputStr) {
        if (null != outputStr) {
            // 注意编码格式,防止中文乱码
            try {
                outputStream.write(outputStr.getBytes("UTF-8"));
                // 释放资源
                outputStream.close();
                outputStream = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private String getResponse(InputStream inputStream) {
        // 将返回的输入流转换成字符串
        InputStreamReader inputStreamReader = null;
        StringBuffer buffer = new StringBuffer();
        try {
            inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }


展开阅读全文

没有更多推荐了,返回首页