欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2022-03-10 22:36:09
注意访问网络必须在分线程执行xml布局文件

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

xml布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <EditText
        android:id="@+id/et_network_url"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textUri"
        android:text="http://192.168.56.1:8080/Web_Server/index.jsp" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="测试HttpUrlConnection" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="urlConnectionGet"
            android:text="GET请求" />

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="urlConnectionPost"
            android:text="POST请求" />
    </LinearLayout>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="测试OkHttpClient" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="OkHttpClientGet"
            android:text="GET请求" />

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="OkHttpClientPost"
            android:text="POST请求" />

    </LinearLayout>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="测试Volley框架" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="volleyGet"
            android:text="GET请求" />

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="volleyPost"
            android:text="POST请求" />
    </LinearLayout>

    <EditText
        android:id="@+id/et_network_result"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="用来显示数据返回的结果" />
</LinearLayout>

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<String>() {
            //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<String>() {
            @Override
            public void onResponse(String response) {
                et_network_result.setText(response);
                dialog.dismiss();
            }

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

访问网络权限

 <uses-permission android:name="android.permission.INTERNET" />

允许使用http  <application 下

android:usesCleartextTraffic="true"

 

本文地址:https://blog.csdn.net/we1less/article/details/107892391