Android 网络请求方式

前言

最近需要将Android 项目接入物联网公司提供的接口,所以顺便给大家分享一下Android中我们常用的网络请求吧!提醒大家一下,我们遇到接口需求,一定要先在Postman上测试接口是否正确,然后再去项目上写程序来请求接口;否则,请求出问题,你都不确定是你程序写的有问题还是接口本身提供的有问题。

Android网络请求程序演练

HttpUrlConnection

这是 Android 中最常用的网络请求方式,可以通过该类建立连接并进行 HTTP 请求和响应的读写操作。使用简单,支持多种数据格式。

GET请求

java 复制代码
public void sendGetRequest() {
    String url = "http://example.com/api/getData";
    HttpURLConnection connection = null;

    try {
        URL requestUrl = new URL(url);
        connection = (HttpURLConnection) requestUrl.openConnection();
        connection.setRequestMethod("GET");

        // 添加header
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "application/json");

        // 设置连接和读取超时时间
        connection.setConnectTimeout(8000);
        connection.setReadTimeout(8000);

        int responseCode = connection.getResponseCode();
        if (responseCode == 200) { // 请求成功
            InputStream inputStream = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder builder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }

            String response = builder.toString();
            Log.d(TAG, "response: " + response);
        } else { // 请求失败
            Log.e(TAG, "Error response code: " + responseCode);
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

其中,我们使用HttpURLConnection的openConnection()方法打开一个连接,然后设置请求方式为GET,再添加headers,设置连接和读取超时时间,最后通过getResponseCode()方法获取响应码,如果是200则表示请求成功,接着就可以获取响应数据了。

POST请求

java 复制代码
public class MainActivity extends AppCompatActivity {
    
    private EditText editText;
    private TextView textView;
    private String url = "http://example.com/api";
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        editText = findViewById(R.id.editText);
        textView = findViewById(R.id.textView);
        
        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String postData = editText.getText().toString().trim();
                if (!TextUtils.isEmpty(postData)) {
                    new PostTask().execute(postData);
                } else {
                    Toast.makeText(MainActivity.this, "请输入内容", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
    
    private class PostTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            try {
                URL reqUrl = new URL(url);
                HttpURLConnection conn = (HttpURLConnection) reqUrl.openConnection();
                conn.setReadTimeout(10000);
                conn.setConnectTimeout(15000);
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
                OutputStream outputStream = conn.getOutputStream();
                outputStream.write(params[0].getBytes("UTF-8"));
                outputStream.flush();
                outputStream.close();
                int responseCode = conn.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    InputStream inputStream = conn.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                    StringBuilder response = new StringBuilder();
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    reader.close();
                    inputStream.close();
                    return response.toString();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
        
        @Override
        protected void onPostExecute(String result) {
            if (result != null) {
                textView.setText(result);
            } else {
                Toast.makeText(MainActivity.this, "请求出错", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

Volley

Volley 是 Google 推出的一款网络请求框架,专门用于简化 Android 应用开发中的网络请求,具有自动请求队列、网络请求缓存、图片加载等功能。

GET请求

java 复制代码
// 创建一个 RequestQueue 对象
RequestQueue queue = Volley.newRequestQueue(this);

// 指定请求的 URL
String url = "https://www.example.com/api/get_data";

// 创建一个 StringRequest 对象
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                // 响应成功时的回调函数
                Log.d(TAG, "Response: " + response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // 响应失败时的回调函数
                Log.e(TAG, "Error: " + error.getMessage());
            }
        });

// 将 StringRequest 对象添加到 RequestQueue 中
queue.add(stringRequest);

POST请求

java 复制代码
RequestQueue queue = Volley.newRequestQueue(this);
String url = "http://your-url.com/post-endpoint";
StringRequest postRequest = new StringRequest(Request.Method.POST, url, 
    new Response.Listener<String>() 
    {
        @Override
        public void onResponse(String response) {
            // 处理响应
        }
    }, 
    new Response.ErrorListener() 
    {
         @Override
         public void onErrorResponse(VolleyError error) {
             // 处理错误
         }
    }
) {     
    @Override
    protected Map<String, String> getParams() 
    {  
        // 请求参数
        Map<String, String> params = new HashMap<String, String>();  
        params.put("param1", "value1");  
        params.put("param2", "value2");  

        return params;  
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> headers = new HashMap<String, String>();
        // 添加headers
        headers.put("Authorization", "Bearer your-access-token");
        return headers;
    }
};

queue.add(postRequest);

Retrofit

Retrofit 是一个基于 OkHttp 的类型安全的 RESTful 客户端,可以使用注解的方式实现接口的定义,高效易用,支持多种数据格式。

GET请求

  1. 添加Retrofit依赖项:在您的Android项目中的build.gradle文件中添加以下依赖项:

    dependencies {
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
    }

  2. 创建Retrofit实例:在您的Java类中创建Retrofit实例。

    Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://yourapi.com/")
    .addConverterFactory(GsonConverterFactory.create())
    .build();

  3. 创建API接口:创建一个Java接口,其中定义GET请求以及其参数和返回类型。

    public interface YourApiService {
    @GET("your_api_path")
    Call<YourApiResponse> getYourApiData(@Query("your_param_name") String yourParamValue);
    }

  4. 发送GET请求:在您的Java类中使用Retrofit实例创建API服务实例,并发送GET请求。这可以在Activity或Fragment中完成,也可以使用ViewModel和LiveData进行MVVM架构。

    YourApiService apiService = retrofit.create(YourApiService.class);

    Call<YourApiResponse> call = apiService.getYourApiData("your_param_value");

    call.enqueue(new Callback<YourApiResponse>() {
    @Override
    public void onResponse(Call<YourApiResponse> call, Response<YourApiResponse> response) {
    // 处理响应
    }

    复制代码
      @Override
      public void onFailure(Call<YourApiResponse> call, Throwable t) {
            // 处理失败
      }

    });

在上面的代码中,我们使用enqueue()方法异步发送GET请求,并在回调方法中处理响应。我们可以在onResponse()方法中处理成功的响应,并在onFailure()方法中处理失败的响应。

POST请求

使用Retrofit发送POST请求需要创建一个接口,接口中定义请求的参数和返回值类型,在方法上使用@POST注解,并且指定请求的URL,参数使用@Body注解标识。下面是一个简单的示例:

首先,添加Retrofit的依赖:

复制代码
implementation 'com.squareup.retrofit2:retrofit:2.9.0'

然后,定义一个接口,例如:

java 复制代码
public interface ApiInterface {

    @POST("login")
    Call<ResponseBody> login(@Body LoginRequest request);

}

其中,@POST("login")表示请求的URL为"login",@Body LoginRequest request表示请求的参数为一个LoginRequest对象。

接下来,创建一个Retrofit实例,并调用接口中的请求方法,例如:

java 复制代码
//创建Retrofit实例
Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .build();
//创建接口实例
ApiInterface apiInterface = retrofit.create(ApiInterface.class);
//创建请求对象
LoginRequest request = new LoginRequest("username", "password");
//发送请求
Call<ResponseBody> call = apiInterface.login(request);
call.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
        //请求成功处理逻辑
    }

    @Override
    public void onFailure(Call<ResponseBody> call, Throwable t) {
        //请求失败处理逻辑
    }
});

其中,BASE_URL需要替换为你的服务器地址,LoginRequest为请求参数的实体类,例如:

java 复制代码
public class LoginRequest {
    private String username;
    private String password;

    public LoginRequest(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

以上就是通过Retrofit发送POST请求的基本流程。

OkHttp

OkHttp 是一个高效的 HTTP 客户端,支持 HTTP/2 和持久连接,可以用于替代 HttpUrlConnection 和 Volley。

GET请求

java 复制代码
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
        .url("https://www.example.com/get")
        .build();
try {
    Response response = client.newCall(request).execute();
    String responseData = response.body().string();
    Log.d(TAG, "onResponse: " + responseData);
} catch (IOException e) {
    e.printStackTrace();
}

POST请求

以下是一个使用OkHttp同步发送POST请求的示例代码:

java 复制代码
OkHttpClient client = new OkHttpClient();

// 构造请求体,这里使用JSON格式
String json = "{\"username\":\"admin\",\"password\":\"123456\"}";
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), json);

// 构造请求对象
Request request = new Request.Builder()
        .url("http://www.example.com/login") // 请求URL
        .addHeader("Content-Type", "application/json") // 设置请求头
        .post(requestBody) // 设置请求体
        .build();

// 创建Call对象并发起请求
Call call = client.newCall(request);
Response response = call.execute();

// 解析响应结果
String result = response.body().string();

需要注意的是,如果请求过程需要很长时间,建议使用enqueue方法异步发起请求,避免阻塞主线程。例如:

java 复制代码
OkHttpClient client = new OkHttpClient();

// 构造请求体
String json = "{\"username\":\"admin\",\"password\":\"123456\"}";
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), json);

// 构造请求对象
Request request = new Request.Builder()
        .url("http://www.example.com/login") // 请求URL
        .addHeader("Content-Type", "application/json") // 设置请求头
        .post(requestBody) // 设置请求体
        .build();

// 创建Call对象并异步发起请求
Call call = client.newCall(request);
call.enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        // 处理请求失败的情况
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        // 处理响应结果
        String result = response.body().string();
    }
});

AsyncHttpClient

AsyncHttpClient 是一个轻量级的异步 HTTP 客户端,支持 HTTP、HTTPS、WebSocket 和 HTTP2.0 协议,可以实现全局的请求头和请求参数的设置。

GET请求

java 复制代码
AsyncHttpClient client = new AsyncHttpClient();
String url = "https://www.example.com/api/data";
RequestParams params = new RequestParams();
params.put("param1", "value1");
params.put("param2", "value2");

client.get(url, params, new AsyncHttpResponseHandler() {
    @Override
    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
        // 请求成功
        String response = new String(responseBody);
        Log.d("AsyncHttpClient", "Response: " + response);
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
        // 请求失败
        Log.e("AsyncHttpClient", "Error: " + error.getMessage());
    }
});

POST请求

java 复制代码
String url = "http://example.com/api/post";
client.post(url, params, new AsyncHttpResponseHandler() {

    @Override
    public void onStart() {
        // 发送请求前调用
    }

    @Override
    public void onSuccess(int statusCode, Header[] headers, byte[] response) {
        // 请求成功调用, statusCode为HTTP状态码
        String result = new String(response);
        Log.i(TAG, "onSuccess: " + result);
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
        // 请求失败调用,statusCode为HTTP状态码
        Log.e(TAG, "onFailure: statusCode=" + statusCode, e);
    }

    @Override
    public void onRetry(int retryNo) {
        // 请求重试调用
    }
});
相关推荐
檀越剑指大厂2 小时前
容器化 Android 开发效率:cpolar 内网穿透服务优化远程协作流程
android
MiyamuraMiyako3 小时前
从 0 到发布:Gradle 插件双平台(MavenCentral + Plugin Portal)发布记录与避坑
android
NRatel3 小时前
Unity 游戏提升 Android TargetVersion 相关记录
android·游戏·unity·提升版本
叽哥6 小时前
Kotlin学习第 1 课:Kotlin 入门准备:搭建学习环境与认知基础
android·java·kotlin
风往哪边走6 小时前
创建自定义语音录制View
android·前端
用户2018792831676 小时前
事件分发之“官僚主义”?或“绕圈”的艺术
android
用户2018792831676 小时前
Android事件分发为何喜欢“兜圈子”?不做个“敞亮人”!
android
Kapaseker8 小时前
你一定会喜欢的 Compose 形变动画
android
QuZhengRong8 小时前
【数据库】Navicat 导入 Excel 数据乱码问题的解决方法
android·数据库·excel
zhangphil9 小时前
Android Coil3视频封面抽取封面帧存Disk缓存,Kotlin(2)
android·kotlin