访问远程服务器 之 httpUrlConnection(原生)OkHttp(框架)volley(框架)

注意访问网络必须在分线程执行

xml布局文件




    

    

    

        

activity代码--使用httpUrlConnection实现Get

  //使用httpUrlConnection实现Get
    public void urlConnectionGet(View view) {
        Log.i("godv", "urlConnectionGet");
        //显示progressDialog
        final ProgressDialog dialog = ProgressDialog.show(this, null, "正在请求中");
        //启动分线程  发送数据 得到响应
        new Thread() {
            public void run() {
                Log.i("godv", "run");
                //创建url对象
                String path = et_network_url.getText().toString() + "?name=godv&age=17";
                Log.i("godv", "path = " + path);
                try {
                    URL url = new URL(path);
                    //打开连接 url.openConnection()返回URLConnection接口
                    //但是这里我们需要一个实现类
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    Log.i("godv", "HttpURLConnection = " + connection);
                    //设置请求方式 连接超时时间 读取数据超时时间
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(6000);
                    connection.setReadTimeout(6000);
                    Log.i("godv", "setReadTimeout");
                    //连接服务器
                    connection.connect();
                    Log.i("godv", "connection = " + connection);
                    //得到响应码
                    int responseCode = connection.getResponseCode();
                    Log.i("godv", "responseCode = " + responseCode);
                    if (responseCode == 200) {
                        //得到输入流 写数据
                        InputStream is = connection.getInputStream();
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        byte[] buffer = new byte[1024];
                        int len = -1;
                        while ((len = is.read(buffer)) != -1) {
                            baos.write(buffer, 0, len);
                        }
                        final String result = baos.toString();
                        Log.i("godv", result);
                        baos.close();
                        is.close();
                        //在主线程更新界面
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                et_network_result.setText(result);
                                dialog.dismiss();
                            }
                        });
                    }
                    //断开连接
                    connection.disconnect();

                } catch (Exception e) {
                    Log.i("godv", "异常 = " + e.getMessage());
                }
            }
        }.start();
    }

使用httpUrlConnection实现Post

 public void urlConnectionPost(View view) {
        //显示progressDialog
        final ProgressDialog dialog = ProgressDialog.show(this, null, "正在请求中");
        //启动分线程  发送数据 得到响应
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.i("godv", "run");
                //创建url对象
                String path = et_network_url.getText().toString();
                Log.i("godv", "path = " + path);
                try {
                    URL url = new URL(path);
                    //打开连接 url.openConnection()返回URLConnection接口
                    //但是这里我们需要一个实现类
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    Log.i("godv", "HttpURLConnection = " + connection);
                    //设置请求方式 连接超时时间 读取数据超时时间
                    connection.setRequestMethod("POST");
                    connection.setConnectTimeout(5000);
                    connection.setReadTimeout(6000);
                    Log.i("godv", "setReadTimeout");
                    //连接服务器
                    connection.connect();
                    Log.i("godv", "connection = " + connection);
                    //得到输出流  写请求体
                    OutputStream os = connection.getOutputStream();
                    String data = "name=godv&age=11";
                    os.write(data.getBytes("utf-8"));
                    //得到响应码
                    int responseCode = connection.getResponseCode();
                    Log.i("godv", "responseCode = " + responseCode);
                    if (responseCode == 200) {
                        //得到输入流 写数据
                        InputStream is = connection.getInputStream();
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        byte[] buffer = new byte[1024];
                        int len = -1;
                        while ((len = is.read(buffer)) != -1) {
                            baos.write(buffer, 0, len);
                        }
                        final String result = baos.toString();
                        Log.i("godv", result);
                        baos.close();
                        is.close();
                        //在主线程更新界面
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                et_network_result.setText(result);
                                dialog.dismiss();
                            }
                        });
                    }
                    os.close();
                    //断开连接
                    connection.disconnect();
                } catch (Exception e) {
                    Log.i("godv", "异常 = " + e.getMessage());
                }
            }
        }).start();
    }

 使用OkHttpClient实现Get

依赖

implementation 'com.squareup.okhttp3:okhttp:3.10.0'

分享个文章关于 OkHttpClient使用的https://www.jianshu.com/p/da4a806e599b

 public void OkHttpClientGet(View view) {
        Log.i("godv", "urlConnectionGet");
        //显示progressDialog
        final ProgressDialog dialog = ProgressDialog.show(this, null, "正在请求中");

        try {
            Log.i("godv", "run");
            //创建url对象
            String path = et_network_url.getText().toString() + "?name=godv&age=17";
            Log.i("godv", "path = " + path);

            //创建OkHttpClient对象
            OkHttpClient okHttpClient = new OkHttpClient();

            // 得到 request对象 并设置url
            final Request request = new Request.Builder()
                    .url(path)
                    .get()//默认就是GET请求,可以不写
                    .build();
            //通过前两步中的对象构建Call对象
            Call call = okHttpClient.newCall(request);
            //通过Call#enqueue(Callback)方法来提交异步请求
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.d("godv", "onFailure: ");
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
//                    Log.d("godv", "onResponse: " + response.body().string());
                    //得到响应体文本
                    final String result = response.body().string();
                    //在主线程更新界面
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            et_network_result.setText(result);
                            dialog.dismiss();
                        }
                    });
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 使用OkHttpClient实现Post

  public void OkHttpClientPost(View view) {
        Log.i("godv", "urlConnectionGet");
        //显示progressDialog
        final ProgressDialog dialog = ProgressDialog.show(this, null, "正在请求中");

        RequestBody requestBody = new FormBody.Builder()
                .add("name", "godv")
                .add("age", "99")
                .build();

        try {
            Log.i("godv", "run");
            //创建url对象
            String path = et_network_url.getText().toString();
            Log.i("godv", "path = " + path);
            //创建OkHttpClient对象
            OkHttpClient okHttpClient = new OkHttpClient();

            // 得到 request对象 并设置url
            final Request request = new Request.Builder()
                    .url(path)
                    .post(requestBody)
                    .build();
            //通过前两步中的对象构建Call对象
            okHttpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.d("godv", "onFailure: " + e.getMessage());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    Log.d("godv", response.protocol() + " " + response.code() + " " + response.message());
                    Headers headers = response.headers();
                    for (int i = 0; i < headers.size(); i++) {
                        Log.d("godv", headers.name(i) + ":" + headers.value(i));
                    }
//                    Log.d("godv", "onResponse: " + response.body().string());
                    final String result = response.body().string();
                    //在主线程更新界面
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            et_network_result.setText(result);
                            dialog.dismiss();
                        }
                    });
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

  使用Volley实现Get

依赖

implementation 'com.android.volley:volley:1.1.1'

分享个文章关于 Volley使用的https://blog.csdn.net/u010356768/article/details/87720280 

创建 RequestQueue 队列  1次 在onCreate 中创建 )

RequestQueue queue;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    queue = Volley.newRequestQueue(this);
}

    public void volleyGet(View view) {
        final ProgressDialog dialog = ProgressDialog.show(this, null, "正在请求中");
        //创建请求对象 StringRequest
        //创建url
        String path = et_network_url.getText().toString() + "?name=godv&age=14";
        //参数二
        StringRequest request = new StringRequest(path, new com.android.volley.Response.Listener() {
            //onResponse 在主线程执行
            @Override
            public void onResponse(String response) {
                et_network_result.setText(response);
                dialog.dismiss();
            }
        }, null);
        //添加请求至队列
        queue.add(request);
    }

 使用Volley实现Post

public void volleyPost(View view) {
        final ProgressDialog dialog = ProgressDialog.show(this, null, "正在请求中");
        //创建请求对象 StringRequest
        //创建url
        String path = et_network_url.getText().toString();
        //参数二
        StringRequest request = new StringRequest(com.android.volley.Request.Method.POST, path, new com.android.volley.Response.Listener() {
            @Override
            public void onResponse(String response) {
                et_network_result.setText(response);
                dialog.dismiss();
            }

        }, null) {
            //重写getParams  返回参数map作为请求体
            @Override
            protected Map getParams() throws AuthFailureError {
                Map map = new HashMap<>();
                map.put("name", "godv");
                map.put("age", "12");
                return map;
            }
        };
        //添加请求至队列
        queue.add(request);
    }

访问网络权限

 

允许使用http  

android:usesCleartextTraffic="true"

 

你可能感兴趣的:(安卓基础学习,android,网络)