• Android 网络请求方式


    前言

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

    Android网络请求程序演练

    HttpUrlConnection

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

    GET请求

    1. public void sendGetRequest() {
    2. String url = "http://example.com/api/getData";
    3. HttpURLConnection connection = null;
    4. try {
    5. URL requestUrl = new URL(url);
    6. connection = (HttpURLConnection) requestUrl.openConnection();
    7. connection.setRequestMethod("GET");
    8. // 添加header
    9. connection.setRequestProperty("Content-Type", "application/json");
    10. connection.setRequestProperty("Accept", "application/json");
    11. // 设置连接和读取超时时间
    12. connection.setConnectTimeout(8000);
    13. connection.setReadTimeout(8000);
    14. int responseCode = connection.getResponseCode();
    15. if (responseCode == 200) { // 请求成功
    16. InputStream inputStream = connection.getInputStream();
    17. BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    18. StringBuilder builder = new StringBuilder();
    19. String line;
    20. while ((line = reader.readLine()) != null) {
    21. builder.append(line);
    22. }
    23. String response = builder.toString();
    24. Log.d(TAG, "response: " + response);
    25. } else { // 请求失败
    26. Log.e(TAG, "Error response code: " + responseCode);
    27. }
    28. } catch (Exception e) {
    29. e.printStackTrace();
    30. } finally {
    31. if (connection != null) {
    32. connection.disconnect();
    33. }
    34. }
    35. }

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

    POST请求

    1. public class MainActivity extends AppCompatActivity {
    2. private EditText editText;
    3. private TextView textView;
    4. private String url = "http://example.com/api";
    5. @Override
    6. protected void onCreate(Bundle savedInstanceState) {
    7. super.onCreate(savedInstanceState);
    8. setContentView(R.layout.activity_main);
    9. editText = findViewById(R.id.editText);
    10. textView = findViewById(R.id.textView);
    11. Button button = findViewById(R.id.button);
    12. button.setOnClickListener(new View.OnClickListener() {
    13. @Override
    14. public void onClick(View view) {
    15. String postData = editText.getText().toString().trim();
    16. if (!TextUtils.isEmpty(postData)) {
    17. new PostTask().execute(postData);
    18. } else {
    19. Toast.makeText(MainActivity.this, "请输入内容", Toast.LENGTH_SHORT).show();
    20. }
    21. }
    22. });
    23. }
    24. private class PostTask extends AsyncTask {
    25. @Override
    26. protected String doInBackground(String... params) {
    27. try {
    28. URL reqUrl = new URL(url);
    29. HttpURLConnection conn = (HttpURLConnection) reqUrl.openConnection();
    30. conn.setReadTimeout(10000);
    31. conn.setConnectTimeout(15000);
    32. conn.setRequestMethod("POST");
    33. conn.setDoInput(true);
    34. conn.setDoOutput(true);
    35. conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
    36. OutputStream outputStream = conn.getOutputStream();
    37. outputStream.write(params[0].getBytes("UTF-8"));
    38. outputStream.flush();
    39. outputStream.close();
    40. int responseCode = conn.getResponseCode();
    41. if (responseCode == HttpURLConnection.HTTP_OK) {
    42. InputStream inputStream = conn.getInputStream();
    43. BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
    44. StringBuilder response = new StringBuilder();
    45. String line = null;
    46. while ((line = reader.readLine()) != null) {
    47. response.append(line);
    48. }
    49. reader.close();
    50. inputStream.close();
    51. return response.toString();
    52. }
    53. } catch (Exception e) {
    54. e.printStackTrace();
    55. }
    56. return null;
    57. }
    58. @Override
    59. protected void onPostExecute(String result) {
    60. if (result != null) {
    61. textView.setText(result);
    62. } else {
    63. Toast.makeText(MainActivity.this, "请求出错", Toast.LENGTH_SHORT).show();
    64. }
    65. }
    66. }
    67. }

    Volley

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

    GET请求

    1. // 创建一个 RequestQueue 对象
    2. RequestQueue queue = Volley.newRequestQueue(this);
    3. // 指定请求的 URL
    4. String url = "https://www.example.com/api/get_data";
    5. // 创建一个 StringRequest 对象
    6. StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
    7. new Response.Listener() {
    8. @Override
    9. public void onResponse(String response) {
    10. // 响应成功时的回调函数
    11. Log.d(TAG, "Response: " + response);
    12. }
    13. }, new Response.ErrorListener() {
    14. @Override
    15. public void onErrorResponse(VolleyError error) {
    16. // 响应失败时的回调函数
    17. Log.e(TAG, "Error: " + error.getMessage());
    18. }
    19. });
    20. // 将 StringRequest 对象添加到 RequestQueue 中
    21. queue.add(stringRequest);

    POST请求

    1. RequestQueue queue = Volley.newRequestQueue(this);
    2. String url = "http://your-url.com/post-endpoint";
    3. StringRequest postRequest = new StringRequest(Request.Method.POST, url,
    4. new Response.Listener()
    5. {
    6. @Override
    7. public void onResponse(String response) {
    8. // 处理响应
    9. }
    10. },
    11. new Response.ErrorListener()
    12. {
    13. @Override
    14. public void onErrorResponse(VolleyError error) {
    15. // 处理错误
    16. }
    17. }
    18. ) {
    19. @Override
    20. protected Map getParams()
    21. {
    22. // 请求参数
    23. Map params = new HashMap();
    24. params.put("param1", "value1");
    25. params.put("param2", "value2");
    26. return params;
    27. }
    28. @Override
    29. public Map getHeaders() throws AuthFailureError {
    30. Map headers = new HashMap();
    31. // 添加headers
    32. headers.put("Authorization", "Bearer your-access-token");
    33. return headers;
    34. }
    35. };
    36. queue.add(postRequest);

    Retrofit

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

    GET请求

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

    1. dependencies {
    2. implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    3. implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
    4. }

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

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

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

    1. public interface YourApiService {
    2. @GET("your_api_path")
    3. Call getYourApiData(@Query("your_param_name") String yourParamValue);
    4. }

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

    1. YourApiService apiService = retrofit.create(YourApiService.class);
    2. Call<YourApiResponse> call = apiService.getYourApiData("your_param_value");
    3. call.enqueue(new Callback<YourApiResponse>() {
    4. @Override
    5. public void onResponse(Call<YourApiResponse> call, Response<YourApiResponse> response) {
    6. // 处理响应
    7. }
    8. @Override
    9. public void onFailure(Call<YourApiResponse> call, Throwable t) {
    10. // 处理失败
    11. }
    12. });

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

    POST请求

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

    首先,添加Retrofit的依赖:

    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    

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

    1. public interface ApiInterface {
    2. @POST("login")
    3. Call login(@Body LoginRequest request);
    4. }

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

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

    1. //创建Retrofit实例
    2. Retrofit retrofit = new Retrofit.Builder()
    3. .baseUrl(BASE_URL)
    4. .addConverterFactory(GsonConverterFactory.create())
    5. .build();
    6. //创建接口实例
    7. ApiInterface apiInterface = retrofit.create(ApiInterface.class);
    8. //创建请求对象
    9. LoginRequest request = new LoginRequest("username", "password");
    10. //发送请求
    11. Call call = apiInterface.login(request);
    12. call.enqueue(new Callback() {
    13. @Override
    14. public void onResponse(Call call, Response response) {
    15. //请求成功处理逻辑
    16. }
    17. @Override
    18. public void onFailure(Call call, Throwable t) {
    19. //请求失败处理逻辑
    20. }
    21. });

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

    1. public class LoginRequest {
    2. private String username;
    3. private String password;
    4. public LoginRequest(String username, String password) {
    5. this.username = username;
    6. this.password = password;
    7. }
    8. public String getUsername() {
    9. return username;
    10. }
    11. public void setUsername(String username) {
    12. this.username = username;
    13. }
    14. public String getPassword() {
    15. return password;
    16. }
    17. public void setPassword(String password) {
    18. this.password = password;
    19. }
    20. }

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

    OkHttp

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

    GET请求

    1. OkHttpClient client = new OkHttpClient();
    2. Request request = new Request.Builder()
    3. .url("https://www.example.com/get")
    4. .build();
    5. try {
    6. Response response = client.newCall(request).execute();
    7. String responseData = response.body().string();
    8. Log.d(TAG, "onResponse: " + responseData);
    9. } catch (IOException e) {
    10. e.printStackTrace();
    11. }

    POST请求

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

    1. OkHttpClient client = new OkHttpClient();
    2. // 构造请求体,这里使用JSON格式
    3. String json = "{\"username\":\"admin\",\"password\":\"123456\"}";
    4. RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), json);
    5. // 构造请求对象
    6. Request request = new Request.Builder()
    7. .url("http://www.example.com/login") // 请求URL
    8. .addHeader("Content-Type", "application/json") // 设置请求头
    9. .post(requestBody) // 设置请求体
    10. .build();
    11. // 创建Call对象并发起请求
    12. Call call = client.newCall(request);
    13. Response response = call.execute();
    14. // 解析响应结果
    15. String result = response.body().string();

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

    1. OkHttpClient client = new OkHttpClient();
    2. // 构造请求体
    3. String json = "{\"username\":\"admin\",\"password\":\"123456\"}";
    4. RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), json);
    5. // 构造请求对象
    6. Request request = new Request.Builder()
    7. .url("http://www.example.com/login") // 请求URL
    8. .addHeader("Content-Type", "application/json") // 设置请求头
    9. .post(requestBody) // 设置请求体
    10. .build();
    11. // 创建Call对象并异步发起请求
    12. Call call = client.newCall(request);
    13. call.enqueue(new Callback() {
    14. @Override
    15. public void onFailure(Call call, IOException e) {
    16. // 处理请求失败的情况
    17. }
    18. @Override
    19. public void onResponse(Call call, Response response) throws IOException {
    20. // 处理响应结果
    21. String result = response.body().string();
    22. }
    23. });

    AsyncHttpClient

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

    GET请求

    1. AsyncHttpClient client = new AsyncHttpClient();
    2. String url = "https://www.example.com/api/data";
    3. RequestParams params = new RequestParams();
    4. params.put("param1", "value1");
    5. params.put("param2", "value2");
    6. client.get(url, params, new AsyncHttpResponseHandler() {
    7. @Override
    8. public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
    9. // 请求成功
    10. String response = new String(responseBody);
    11. Log.d("AsyncHttpClient", "Response: " + response);
    12. }
    13. @Override
    14. public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
    15. // 请求失败
    16. Log.e("AsyncHttpClient", "Error: " + error.getMessage());
    17. }
    18. });

    POST请求

    1. String url = "http://example.com/api/post";
    2. client.post(url, params, new AsyncHttpResponseHandler() {
    3. @Override
    4. public void onStart() {
    5. // 发送请求前调用
    6. }
    7. @Override
    8. public void onSuccess(int statusCode, Header[] headers, byte[] response) {
    9. // 请求成功调用, statusCode为HTTP状态码
    10. String result = new String(response);
    11. Log.i(TAG, "onSuccess: " + result);
    12. }
    13. @Override
    14. public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
    15. // 请求失败调用,statusCode为HTTP状态码
    16. Log.e(TAG, "onFailure: statusCode=" + statusCode, e);
    17. }
    18. @Override
    19. public void onRetry(int retryNo) {
    20. // 请求重试调用
    21. }
    22. });

  • 相关阅读:
    Springboot毕设项目办公用品在线销售系统25f35(java+VUE+Mybatis+Maven+Mysql)
    卷积神经网络 - 图像卷积
    Spring 接口日志切片记录
    申请HTTPS证书
    cmd打开idea
    【pytorch】从零开始,利用yolov5、crnn+ctc进行车牌识别
    Windows10专业版系统安装Hyper-V虚拟机软件
    9.25
    Android 天气APP(三十六)运行到本地AS、更新项目版本依赖、去掉ButterKnife
    Dubbo-RPC核心接口介绍
  • 原文地址:https://blog.csdn.net/Ai1114/article/details/132829990