Android 中使用HttpURLConnection进行网络请求详解

简介: Android 中使用HttpURLConnection进行网络请求详解

前言:下面使用HttpURLConnection进行POST的请求,GET请求不需要传递参数自然你也就会使用了。

一、创建UrlConnManager类,提供getHttpURLConnection()方法,配置默认参数,并返回HttpURLConnection的实例。

之后再写一个postParams方法,组织一下请求参数 并将请求参数写入输出流。

代码如下:

public class UrlConnManager {
    //配置默认参数,返回HttpURLConnection的实例
    public static HttpURLConnection getHttpURLConnection(String url) {
        HttpURLConnection httpURLConnection = null;
        try {
            URL mUrl = new URL(url);
            httpURLConnection = (HttpURLConnection) mUrl.openConnection();
            //设置连接超时时间
            httpURLConnection.setConnectTimeout(15000);
            //设置读取超时时间
            //开始读取服务器端数据,到了指定时间还没有读到数据,则报超时异常
            httpURLConnection.setReadTimeout(15000);
            //设置请求参数
            httpURLConnection.setRequestMethod("POST");
            //添加Header
            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            //接收输入流
            httpURLConnection.setDoInput(true);
            //传递参数时,需要开启
            httpURLConnection.setDoOutput(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return httpURLConnection;
    }
    //将请求参数写入到输出流,写出到服务器
    public static void postParams(OutputStream output, List<NameValuePair> paramsList) {
        BufferedWriter bufferedWriter = null;
        try {
            StringBuilder stringBuilder = new StringBuilder();
            for (NameValuePair pair : paramsList) {
                if (!TextUtils.isEmpty(stringBuilder)) {
                    stringBuilder.append("&");
                }
                stringBuilder.append(URLEncoder.encode(pair.getName(), "UTF-8"));
                stringBuilder.append("=");
                stringBuilder.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
                bufferedWriter = new BufferedWriter(new OutputStreamWriter(output, "UTF-8"));
                bufferedWriter.write(stringBuilder.toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedWriter != null) {
                    bufferedWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

二、接下来创建一个Activity和对应的xml文件,点击按钮进行网络请求。

1、activity_http_u_r_l_connection.xml 代码如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".activity.HttpURLConnectionActivity">
    <Button
        android:id="@+id/btn_post"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="HttpURLConnection的Post请求" />
    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

2.HttpURLConnectionActivity代码如下:

public class HttpURLConnectionActivity extends AppCompatActivity {
    private Button btn_post;
    private TextView textView;
    //响应状态码
    private int responseCode;
    //请求结果
    private String response;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_http_u_r_l_connection);
        btn_post = findViewById(R.id.btn_post);
        textView = findViewById(R.id.textView);
        btn_post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //使用HttpURLConnection的post请求
                        useHttpUrlConnectionPost("https://ip.taobao.com/service/getIpInfo.php");
                    }
                }).start();
            }
        });
    }
    private void useHttpUrlConnectionPost(String url) {
        InputStream inputStream = null;
        //获取HttpURLConnection的实例
        HttpURLConnection httpURLConnection = UrlConnManager.getHttpURLConnection(url);
        try {
            List<NameValuePair> postParams = new ArrayList<>();
            //添加请求参数
            postParams.add(new NameValuePair("ip", "59.108.54.37"));
            UrlConnManager.postParams(httpURLConnection.getOutputStream(), postParams);
            //建立实际的连接
            httpURLConnection.connect();
            inputStream = httpURLConnection.getInputStream();
            //服务器返回的响应状态码
            responseCode = httpURLConnection.getResponseCode();
            response = convertStreamToString(inputStream);
            //状态码200:表示客户端请求成功
            if (responseCode == HttpURLConnection.HTTP_OK) {
                //在子线程中不能操作UI线程,通过handler在UI线程中进行操作
                handler.sendEmptyMessage(0x00);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == 0x00) {
                textView.setText("响应状态码:" + responseCode + "\n" + "请求结果:" + "\n" + response);
            }
            return true;
        }
    });
    //读取服务器返回的字符串
    private String convertStreamToString(InputStream inputStream) {
        BufferedReader bufferedReader = null;
        StringBuffer stringBuffer = new StringBuffer();
        String line;
        try {
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            while ((line = bufferedReader.readLine()) != null) {
                stringBuffer.append(line).append("\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return stringBuffer.toString();
    }
}

具体注释已经在代码中给出,效果如下:


目录
相关文章
|
1月前
|
数据库 Android开发 开发者
构建高效Android应用:采用Kotlin协程优化网络请求处理
【2月更文挑战第30天】 在移动应用开发领域,网络请求的处理是影响用户体验的关键环节。针对Android平台,利用Kotlin协程能够极大提升异步任务处理的效率和简洁性。本文将探讨如何通过Kotlin协程优化Android应用中的网络请求处理流程,包括协程的基本概念、网络请求的异步执行以及错误处理等方面,旨在帮助开发者构建更加流畅和响应迅速的Android应用。
|
3月前
|
安全 API Android开发
Android网络和数据交互: 解释Retrofit库的作用。
Android网络和数据交互: 解释Retrofit库的作用。
39 0
|
3月前
|
Android开发 开发者
Android网络和数据交互: 请解释Android中的AsyncTask的作用。
Android网络和数据交互: 请解释Android中的AsyncTask的作用。
22 0
|
4月前
|
XML Java Android开发
Android App开发网络通信中使用okhttp下载和上传图片、文件讲解及实战(超详细实现用户注册信息上传 附源码)
Android App开发网络通信中使用okhttp下载和上传图片、文件讲解及实战(超详细实现用户注册信息上传 附源码)
143 0
|
3天前
|
移动开发 Java Android开发
构建高效Android应用:采用Kotlin协程优化网络请求
【4月更文挑战第24天】 在移动开发领域,尤其是对于Android平台而言,网络请求是一个不可或缺的功能。然而,随着用户对应用响应速度和稳定性要求的不断提高,传统的异步处理方式如回调地狱和RxJava已逐渐显示出局限性。本文将探讨如何利用Kotlin协程来简化异步代码,提升网络请求的效率和可读性。我们将深入分析协程的原理,并通过一个实际案例展示如何在Android应用中集成和优化网络请求。
|
11天前
|
Android开发 开发者
Android网络和数据交互: 请解释Android中的AsyncTask的作用。
Android&#39;s AsyncTask simplifies asynchronous tasks for brief background work, bridging UI and worker threads. It involves execute() for starting tasks, doInBackground() for background execution, publishProgress() for progress updates, and onPostExecute() for returning results to the main thread.
11 0
|
11天前
|
网络协议 安全 API
Android网络和数据交互: 什么是HTTP和HTTPS?在Android中如何进行网络请求?
HTTP和HTTPS是网络数据传输协议,HTTP基于TCP/IP,简单快速,HTTPS则是加密的HTTP,确保数据安全。在Android中,过去常用HttpURLConnection和HttpClient,但HttpClient自Android 6.0起被移除。现在推荐使用支持TLS、流式上传下载、超时配置等特性的HttpsURLConnection进行网络请求。
10 0
|
4月前
|
XML JSON Java
Android App网络通信中通过okhttp调用HTTP接口讲解及实战(包括GET、表单格式POST、JSON格式POST 附源码)
Android App网络通信中通过okhttp调用HTTP接口讲解及实战(包括GET、表单格式POST、JSON格式POST 附源码)
173 0
|
3月前
|
JSON Java Android开发
Android网络和数据交互: 请解释Android中的JSON解析库,如Gson。
Android网络和数据交互: 请解释Android中的JSON解析库,如Gson。
24 0
|
4月前
|
XML JSON Android开发
[Android]网络框架之Retrofit(kotlin)
[Android]网络框架之Retrofit(kotlin)
57 0