湛江阿里云代理商: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

相关推荐

  • 阿里云国际站代理商:安骑士端口扫描好不好

    作为一个AI助手,我无法直接评估某个产品的好坏,但是我可以提供一些相关信息给你参考。 安骑士是阿里云国际站提供的一种网络安全服务,其功能之一是进行端口扫描。端口扫描是网络安全中常见的一项技术,用于检查系统或网络中的开放端口,以帮助发现潜在的安全风险。 安骑士端口扫描可能具有以下优点: 安全性:安骑士端口扫描是阿里云提供的服务,具备相应的安全防护措施,可以帮助…

    2023年12月21日
    65300
  • 扬州阿里云代理商:access数据库查询日期格式

    在Access中查询日期格式需要使用日期函数。如果日期存储为文本,则需要将其转换为日期格式。下面列出了一些常用的Access日期函数和示例: Date()函数: 返回当天日期 SELECT * FROM table WHERE date_field = Date(); Year()函数: 返回年份 SELECT * FROM table WHERE Year…

    2024年3月6日
    66700
  • 阿里云短信服务个人申请

    您好!要申请阿里云短信服务,您需要按照以下步骤进行个人申请。 访问阿里云短信服务官方网站(https://www.aliyun.com/product/sms),点击页面上的”立即开通”按钮。 如果您没有阿里云账号,首先需要注册一个新的账号。点击”免费注册”按钮,填写必要的个人信息完成注册。 登录阿里云账号后,…

    2023年10月22日
    67900
  • 阿里云国际站充值:爱快虚拟机如何设置wan

    阿里云国际站充值:爱快虚拟机如何设置WAN 介绍 阿里云是全球领先的云计算服务提供商,其国际站也提供了世界各地用户可充值的功能。本文将介绍如何利用阿里云国际站充值并配置爱快虚拟机的WAN(Wide Area Network)连接。 阿里云优势 阿里云具有以下几个优势: 高性能稳定:阿里云拥有强大的硬件资源和稳定的网络环境,保证用户在使用云服务时的高性能体验。…

    2024年1月8日
    65000
  • 阿里云企业邮箱的邮件收发记录可以按邮件重要性筛选吗?

    阿里云企业邮箱:按邮件重要性筛选的高效管理 阿里云企业邮箱是一款受到众多企业用户青睐的电子邮件服务,凭借其稳定、安全和高效的性能,已经成为许多企业邮件沟通的首选。对于日常业务中,邮件的处理效率是关键因素,阿里云企业邮箱提供了按邮件重要性筛选的功能,帮助用户轻松管理信息,提高工作效率。以下将介绍如何利用这一功能,并展示阿里云企业邮箱的其他优势。 按邮件重要性筛…

    2024年10月31日
    57400

发表回复

登录后才能评论

联系我们

4000-747-360

在线咨询: QQ交谈

邮件:ixuntao@qq.com

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

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