安卓网络请求工具方式 (HttpURLConnection-Httpclient-Xutils-Okhttp-Volley)

网络请求工具类(HttpURLConnection-Httpclient-Xutils-Okhttp-Volley)

Okhttp、Volley依赖

implementation ‘com.squareup.okhttp3:okhttp:3.12.1’
implementation ‘eu.the4thfloor.volley:com.android.volley:2015.05.28’

工具类代码

// An highlighted block
package bw.com.day18;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
import android.widget.ImageView;

import com.android.volley.AuthFailureError;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.acl.LastOwnerException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.logging.Handler;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Utils {
    /**
     * xutils实现下载图片的功能
     * */
    public void xutils_loadImage(ImageView imageView,String url){
        x.image().bind(imageView,url);
    }


    public void xutils_loadJson_get(String url){

        x.http().get(new RequestParams(url), new Callback.CommonCallback<String>(){

            @Override
            public void onSuccess(String result) {
                Log.e("###",result);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    public void xutils_loadJson_post(String url,String page,String num){
        RequestParams params = new RequestParams(url);//请求参数的对象
        params.addQueryStringParameter(page,num);
        x.http().post(params, new Callback.CacheCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.e("###",result);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }

            @Override
            public boolean onCache(String result) {
                return false;
            }
        });
    }

    public String httpUrlConnection_post(String URL){
        try {
            URL url = new URL(URL);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setReadTimeout(200);
            httpURLConnection.setConnectTimeout(200);

            //支持输入和输出
            httpURLConnection.setDoInput(true);//允许输入
            httpURLConnection.setDoOutput(true);//允许输出
            httpURLConnection.setUseCaches(false);


//            httpConn.connect();
//            DataOutputStream out = new DataOutputStream(httpConn.getOutputStream());
//            String params = "phones=" + URLEncoder.encode(strPhoneNumber, "UTF-8");
//            // DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写到流里面
//            out.writeBytes(params);
//            out.flush();
//            out.close();
            httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpURLConnection.connect();
            OutputStream os = httpURLConnection.getOutputStream();
            String pram = "page";
            String value = "2";
            os.write("phone=18335796374&passwd=1111".getBytes());
            os.close();
            Log.e("@@@@",URL);
            if (httpURLConnection.getResponseCode() == 200){
                InputStream is = httpURLConnection.getInputStream();
                byte[] bytes = new byte[1024];
                int len = -1;
                StringBuffer buffer = new StringBuffer();
                while ((len = is.read(bytes))!=-1){
                    buffer.append(new String(bytes,0,len));
                }
                return buffer.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * Okhttp:第三方下载框架
     * get:
     * 同步--线程
     * 异步:
     * post:
     * 同步--线程
     * 异步:
     * */


    //同步GET
    public String Okhttp_GET(String urlPath){
//        OkHttpClient.Builder builder = new OkHttpClient.Builder();
//        builder.connectTimeout(20000, TimeUnit.MICROSECONDS);//设置连接超时
//        builder.readTimeout(4,TimeUnit.MINUTES);//分钟
//
//        OkHttpClient client = builder.build();//客户端
//        //方法一
        Request.Builder builder1 = new Request.Builder();
        builder1.url(urlPath);//访问的网址
        Request request1 = builder1.build();
//        //方法二
//        Request request2 = new Request.Builder().url(urlPath).get().build();
//
//        Call call = client.newCall(request2);
//        Response response;
//        try {
//             response = call.execute();
//            String json = response.body().string();//拿到了json字符串
//            return json;
//            //放线程中
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        Request request  = new Request.Builder().url(urlPath).get().build();
        OkHttpClient client = new OkHttpClient();
        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()){
                String json = response.body().string();
                return json;
            }else{
                //不成功
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
    /**
     * 同步的POST
     * https://www.apiopen.top/createUser?key=00d91e8e0cca2b76f515926a36db68f5&
     * */
    public String Okhttp_POST(String URL){

//        OkHttpClient.Builder cBuilder = new OkHttpClient.Builder();
//        OkHttpClient client = cBuilder.build();
//
//        Request.Builder rBuilder = new Request.Builder();
//        rBuilder.url(URL);
//
//        FormBody.Builder builder = new FormBody.Builder();//表单
//        builder.add("phone","18335796321");
//        builder.add("passwd","123456");
//        FormBody body = builder.build();
//        rBuilder.post(body);
//
//        Request request = rBuilder.build();
//        Call call = client.newCall(request);
//
//        try {
//            Response response = call.execute();
//            String json = response.body().string();
//            return json;
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

        RequestBody body = new FormBody.Builder()
                .add("phone","wwwwwwww")
                .add("passwd","123")
                .build();

        Request request = new Request.Builder().url(URL).post(body).build();
        OkHttpClient client = new OkHttpClient();

        try {
            Response response = client.newCall(request).execute();
            String json = response.body().string();
            return json;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  null;
    }

    /**
     * 异步 GET
     * */

    public void asyncGET(String strUrl){
        final Request request = new Request.Builder().url(strUrl).get().build();//获得请求对象
        OkHttpClient client = new OkHttpClient();//获得客户端对象
        Call call = client.newCall(request);
        call.enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                String str = "获取失败!";
                Log.e("####",str);
            }

            @Override
            public void onResponse( Call call, Response response) throws IOException {
                String json = response.body().string();
                Log.e("####",json);
            }
        });

    }

    public void asyncPOST(String strUrl){
        OkHttpClient client = new OkHttpClient();//获得client
        FormBody body = new FormBody.Builder()
                .add("phone","qqqqqqqqqqq")
                .add("passwd","123")
                .build();
        Request request = new Request.Builder().url(strUrl).post(body).build();
        Call call = client.newCall(request);
        call.enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                String str = "注册失败!";
                Log.e("####",str);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String json = response.body().string();
                Log.e("####",json);
            }
        });
    }

    //volley下载图片
    public void volleyImage(String strUrl, Context context, final ImageView imageView){
        ImageRequest imageRequest = new ImageRequest(strUrl, new com.android.volley.Response.Listener<Bitmap>() {
            @Override
            public void onResponse(Bitmap response) {
                imageView.setImageBitmap(response);
            }
        },300,500,Bitmap.Config.RGB_565,errorListener);

        RequestQueue requestQueue = Volley.newRequestQueue(context);
        requestQueue.add(imageRequest);
        requestQueue.start();
    }

    public void volleyGET(String urlStr, Context context){

        RequestQueue requestQueue = Volley.newRequestQueue(context);//获得volley队列

        StringRequest request = new StringRequest(StringRequest.Method.GET,urlStr,listener,errorListener);

        requestQueue.add(request);//将请求添加到队列
        requestQueue.start();//启动队列

    }


    //结果
    com.android.volley.Response.Listener<String> listener = new com.android.volley.Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.e("###",response);
        }
    };


    com.android.volley.Response.ErrorListener errorListener = new com.android.volley.Response.ErrorListener(){

        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("###","失败!");
        }
    };
    //Post
    public void volleyPOST(String urlStr, Context context){
        RequestQueue requestQueue = Volley.newRequestQueue(context);

        StringRequest request = new StringRequest(StringRequest.Method.POST,urlStr,listener,errorListener){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String,String> map = new HashMap<>();
                map.put("phone","yyyy");
                map.put("passwd","123");
                return map;
            }
        };

        requestQueue.add(request);
        requestQueue.start();



    }

}

Activity代码

// An highlighted block
package bw.com.day18;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;

import java.util.concurrent.ExecutionException;

import bw.com.day1.R;

public class HttpActivity extends AppCompatActivity {
    ImageView imageView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_http);

        imageView = findViewById(R.id.imageview);

//        try {
//            String s = new MyTask().execute("https://www.apiopen.top/createUser?key=00d91e8e0cca2b76f515926a36db68f5&").get();
//            Log.e("###",s);
//        } catch (ExecutionException e) {
//            e.printStackTrace();
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }

//        new Utils().asyncGET("http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&page=1");

//        new Utils().asyncPOST("https://www.apiopen.top/createUser?key=00d91e8e0cca2b76f515926a36db68f5&");

//        new Utils().volleyGET("http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&page=1",this);

//          new Utils().volleyPOST("https://www.apiopen.top/createUser?key=00d91e8e0cca2b76f515926a36db68f5&",this);

            new Utils().volleyImage("https://img02.sogoucdn.com/app/a/100520024/47751b2ef736cef91e5728d50974fc63",this,imageView);
    }


    class MyTask extends AsyncTask<String,String,String>{
        @Override
        protected String doInBackground(String... strings) {
            return new Utils().Okhttp_POST(strings[0]);
        }
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值