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

Posted 路宇

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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();
    

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

以上是关于Android 中使用HttpURLConnection进行网络请求详解的主要内容,如果未能解决你的问题,请参考以下文章

android 连接网络的简单实例

如何使用 HttpUrlConnect 使用 java 查询 Github graphql API

HttpUrlConnect post提交

android中的HttpUrlConnection的使用之一

Android中的网络编程

Android探索之HttpURLConnection网络请求