湛江阿里云代理商:android网络请求工具类

以下是一个简单的Android网络请求工具类,可以方便地进行网络请求。

import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class HttpUtils {
    
    private static Handler mHandler = new Handler(Looper.getMainLooper());
    
    /**
     * 发送GET请求
     *
     * @param url 请求URL
     * @param params 请求参数
     * @param callback 回调函数
     */
    public static void sendGet(String url, HashMap<String, String> params, final HttpCallback callback) {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        if (params != null && !params.isEmpty()) {
            url += "?" + getParams(params);
        }
        final HttpURLConnection connection = getConnection(url, "GET");
        final String response = getResponse(connection);
        if (callback != null) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    callback.onResponse(response);
                }
            });
        }
    }
    
    /**
     * 发送POST请求
     *
     * @param url 请求URL
     * @param params 请求参数
     * @param callback 回调函数
     */
    public static void sendPost(String url, HashMap<String, String> params, final HttpCallback callback) {
        final HttpURLConnection connection = getConnection(url, "POST");
        if (params != null && !params.isEmpty()) {
            String json = JSON.toJSONString(params);
            byte[] bytes = json.getBytes();
            connection.getOutputStream().write(bytes);
        }
        final String response = getResponse(connection);
        if (callback != null) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    callback.onResponse(response);
                }
            });
        }
    }
    
    /**
     * 获取请求参数
     *
     * @param params 请求参数
     * @return
     */
    private static String getParams(HashMap<String, String> params) {
        if (params == null || params.isEmpty()) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = iterator.next();
            sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        String result = sb.toString();
        if (result.endsWith("&")) {
            result = result.substring(0, result.length() - 1);
        }
        return result;
    }
    
    /**
     * 获取HttpURLConnection对象
     *
     * @param url 请求URL
     * @param method 请求方法,GET或POST
     * @return
     */
    private static HttpURLConnection getConnection(String url, String method) {
        HttpURLConnection connection = null;
        try {
            URL mURL = new URL(url);
            connection = (HttpURLConnection) mURL.openConnection();
            connection.setRequestMethod(method);
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("Connection", "Keep-Alive");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return connection;
    }
    
    /**
     * 获取响应结果
     *
     * @param connection HttpURLConnection对象
     * @return
     */
    private static String getResponse(HttpURLConnection connection) {
        StringBuilder sb = new StringBuilder();
        try {
            InputStream is = connection.getInputStream();
            InputStreamReader isr = new InputStreamReader(is, "UTF-8");
            BufferedReader br = new BufferedReader(isr);
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            br.close();
            isr.close();
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
    
    /**
     * Http请求回调函数
     */
    public interface HttpCallback {
        void onResponse(String response);
    }
}

使用方法:

// 发送GET请求
HttpUtils.sendGet("http://example.com/path", null, new HttpUtils.HttpCallback() {
    @Override
    public void onResponse(String response) {
        // 处理响应结果
    }
});

// 发送POST请求
HashMap<String, String> params = new HashMap<>();
params.put("key1", "value1");
params.put("key2", "value2");
HttpUtils.sendPost("http://example.com/path", params, new HttpUtils.HttpCallback() {
    @Override
    public void onResponse(String response) {
        // 处理响应结果
    }
});

注意:在Android中不能在主线程中执行网络请求,需要在子线程或异步任务中执行。本文示例代码中的HttpUtils工具类只提供网络请求相关的代码逻辑,因此没有涉及到线程相关的代码。在实际使用时,建议在异步任务中调用HttpUtils工具类的相关方法。

在 Android 开发中,经常需要跟网络打交道,请求数据、上传图片、下载文件等操作都要用到网络请求工具类。以下是一个简单的封装了 OkHttp 的网络请求工具类,可以供参考:

public class HttpUtil {
    private static final String TAG = "HttpUtil";

    public static void get(String url, Callback callback) {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .build();

        client.newCall(request).enqueue(callback);
    }

    public static void post(String url, RequestBody body, Callback callback) {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        client.newCall(request).enqueue(callback);
    }

    public static void postJson(String url, String json, Callback callback) {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .build();

        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(mediaType, json);

        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        client.newCall(request).enqueue(callback);
    }
}

其中,get() 方法用于发起 GET 请求,post() 方法用于发起 POST 请求,postJson() 方法则用于发起 POST 请求并传递 JSON 数据。

这是一个比较简单的网络请求工具类,大家可以根据自己的需求进行扩展和修改。在使用时,只需要调用对应的方法并提供相应的参数即可。如下面的示例代码:

湛江阿里云代理商:android网络请求工具类
HttpUtil.get("https://www.baidu.com", new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        Log.e(TAG, "request failed!" + e.getMessage());
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        Log.d(TAG, "response body:" + response.body().string());
    }
});

String json = "{"name":"zhangsan", "age":20}";
HttpUtil.postJson("https://httpbin.org/post", json, new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        Log.e(TAG, "request failed!" + e.getMessage());
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        Log.d(TAG, "response body:" + response.body().string());
    }
});

上面的代码分别使用了 get() 和 postJson() 方法发起了 GET 和 POST 请求,并在回调函数中处理了响应结果。需要注意的是,在回调中处理响应结果的时候,需要在子线程中执行,否则会抛出异常。

发布者:luotuoemo,转转请注明出处:https://www.jintuiyun.com/157936.html

(0)
luotuoemo的头像luotuoemo
上一篇 2024年3月7日 16:35
下一篇 2024年3月7日 16:52

相关推荐

  • 湖州阿里云代理商:阿里云服务器远程不到

    湖州阿里云代理商:阿里云服务器远程不到来 简介 阿里云作为全球知名的云计算平台提供商,以其优势和好用之处,成为众多企业的首选。然而,有时用户可能会遇到阿里云服务器远程不到来的问题。本文将重点介绍阿里云的优势和解决服务器远程访问问题的方法。 阿里云的优势 1. 可靠性:阿里云服务器运行在全球分布的数据中心,具备高可用性,能够保证服务的持续稳定运行。 2. 弹性…

    2024年1月15日
    33200
  • 东莞阿里云代理商:api接口怎么搞

    api接口是阿里云提供给开发者进行系统对接和集成的桥梁,可以实现各种功能和服务的调用。下面是关于如何搞api接口的一些步骤: 注册阿里云账号:首先,你需要注册一个阿里云账号。在阿里云官网上填写相关信息完成注册。 创建AccessKey:AccessKey是进行API调用的密钥,通过阿里云控制台创建AccessKey,得到AccessKeyId和AccessK…

    2024年2月11日
    35200
  • 西藏阿里云智创中心

    阿里云网站ICP备案详细操作流程 依据工信部的卖运要求国内网站必须有备案号才能开通,阿里云网站ICP备案是每个在阿里云搭建网站的用户都要操作的。以下的信息务必真实有效,不能有差错,后面阿里云自查、管局检查出来会给你打回来重新填写,耽误下备案号时间。      如果你使用阿里云app备案,请参考阿里云APP备案操作流程      一、备案流程      进入备…

    2023年8月28日
    37000
  • 阿里云哪些配置按流量收费的

    关于阿里云服务器ECS购买的问题。按使用流量:是先使用后付费产品,每小时扣费。0.72元/GB 这个是分开来看的,比如说下图:其中配置费用不管你是不是用,只要买了以后是每小时固定扣;流量费用是网站访问实际造成的流量费用,用多少付多少。这种按量付费方式,系统每个小时扣款一次,需要你在阿里云账号下充值余额,一旦没有余额了,主机就会被关停 阿里云3万日访问量选那种…

    2023年8月27日
    36400
  • 阿里云数据库怎么用navicat连接

    要使用Navicat连接阿里云数据库,需要按照以下步骤操作: 下载并安装最新版本的Navicat软件。 在阿里云数据库管理控制台中,找到要连接的数据库实例,点击该实例旁边的“连接信息”按钮。 在连接信息页面中,找到“内网地址”和“端口号”,记录下这两个信息。 打开Navicat软件,选择“连接” -> “MySQL”。 在连接设置页面,填写以下信息: …

    2023年8月14日
    33900

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

联系我们

4000-747-360

在线咨询: QQ交谈

邮件:ixuntao@qq.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信
购买阿里云服务器请访问:https://www.4526.cn/