Android使用HttpURLConnection,OKHttp发送请求及注意事项

Posted 背时的哥哥

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android使用HttpURLConnection,OKHttp发送请求及注意事项相关的知识,希望对你有一定的参考价值。

文章目录

1.HttpURLConnection的使用

1.编写测试代码

1. 使用ScrollView组件接收网站返回数据

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

    <Button
        android:id="@+id/send_request"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Send Request"/>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/response_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </ScrollView>
</LinearLayout>

2.编写活动

package com.example.networktest;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener 

    TextView responseText;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        Button sendRequest = findViewById(R.id.send_request);
        responseText = findViewById(R.id.response_text);
        sendRequest.setOnClickListener(this);
    

    @Override
    public void onClick(View v) 
        if (v.getId() == R.id.send_request)
            sendRequestWithHttpURLConnection();
        
    


    public void sendRequestWithHttpURLConnection()
        //开启线程发送网络请求
        new Thread(new Runnable() 
            @Override
            public void run() 
                HttpURLConnection connection = null;
                BufferedReader reader = null;
                try
                    URL url = new URL("http://www.baidu.com");
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    InputStream in = connection.getInputStream();
                    //对获取到的输入流进行读取
                    reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while((line = reader.readLine())!=null)
                        response.append(line);
                    
                    showResponse(response.toString());
                catch (Exception e)
                    e.printStackTrace();
                finally 
                    if (reader!=null)
                        try 
                            reader.close();
                         catch (IOException e) 
                            e.printStackTrace();
                        
                    
                    if (connection!=null)
                        connection.disconnect();
                    
                
            
        ).start();
    

//将获取的数据传入ScrollView组件
    private void showResponse(final String response)
        runOnUiThread(new Runnable() 
            @Override
            public void run() 
                responseText.setText(response);
            
        );
    

2.测试结果(注意)

点击button按钮后,你会发现接收不到网站返回的数据结果。不必惊慌,查看官方文档可知!

  • 解决方案一:若使用http传输协议,则需要在AndroidMainfest.xml文件的application标签中修改属性android:usesCleartextTraffic为true
  • 解决方法二:在创建URL对象时,直接使用安全协议https(推荐使用,直接且方便)
  • 解决方案三:
    1.首先编写配置文件network_security_config.xml
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">//可使用http协议
        <domain includeSubdomains="true">www.baidu.com</domain>//指定使用明文协议访问该网站时,不会被拦截
    </domain-config>
</network-security-config>

2.在应用的清单中添加一个指向该文件的条目
<application
		...
        android:networkSecurityConfig="@xml/network_security_config"
        ...
    </application>

修改之后再次运行,结果如下

2.OKHTttp的使用

与HttpURLConnection类似,只需修改少数代码即可。

 public void sendRequestWithOkHttpConnection()
        //开启线程发送网络请求
        new Thread(new Runnable() 
            @Override
            public void run() 
                HttpURLConnection connection = null;
                BufferedReader reader = null;
                try
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder().url("http://www.baidu.com")
                            .build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    showResponse(responseData);
                catch (Exception e)
                    e.printStackTrace();
                finally 
                    if (reader!=null)
                        try 
                            reader.close();
                         catch (IOException e) 
                            e.printStackTrace();
                        
                    
                    if (connection!=null)
                        connection.disconnect();
                    
                
            
        ).start();
    

以上是关于Android使用HttpURLConnection,OKHttp发送请求及注意事项的主要内容,如果未能解决你的问题,请参考以下文章

Android中"get","post"请求的其中三种常用数据提交方式

OkHttp框架从入门到放弃,解析图片使用Picasso裁剪,二次封装OkHttpUtils,Post提交表单数据

java抓取网页数据

JAVA多线程下载

用IO流发送Http请求

Java通过代理server上网