Android之HttpURLConnection的GET和POST请求

本文详细介绍了如何使用Java实现HTTP GET和POST请求的方法,并提供了完整的代码示例。包括如何创建URL对象,打开连接,设置请求参数及超时时间,发送请求并处理响应等。同时,还涉及了如何使用自定义的Toast基类进行错误提示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

GET请求

 public static String requestByGet(Context context,String path) throws Exception{
        String data = "";
        // 新建一个URL对象
        URL url = new URL(path);
        // 打开一个HttpURLConnection连接
        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
        // 设置连接超时时间
        urlConn.setConnectTimeout(3 * 1000);
        // 开始连接
        urlConn.connect();
        // 判断请求是否成功
        if (urlConn.getResponseCode() == 200) {
            // 获取返回的数据
        data = IOUtils.getTextFromStream(urlConn.getInputStream());

        } else {
            ToastUtil.showShort(context,"请求失败");
        }
        // 关闭连接
        urlConn.disconnect();
        return data;
    }

POST请求

public static String requestByPost(Context context,String path)throws Exception{
        String data = "";
        String params = "name="+ URLEncoder.encode("username", "UTF-8")
                + "&password=" + URLEncoder.encode("password", "UTF-8");
        byte[] postData = params.getBytes();
        // 新建一个URL对象
        URL url = new URL(path);
        // 打开一个HttpURLConnection连接
        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
        // 设置连接超时时间
        urlConn.setConnectTimeout(3 * 1000);
        // Post请求必须设置允许输出
        urlConn.setDoOutput(true);
        // Post请求不能使用缓存
        urlConn.setUseCaches(false);
        // 设置为Post请求
        urlConn.setRequestMethod("POST");
        urlConn.setInstanceFollowRedirects(true);
        // 配置请求Content-Type
        urlConn.setRequestProperty("Content-Type","application/x-www-form-urlencode");
        // 开始连接
        urlConn.connect();
        // 发送请求参数
        DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream());
        dos.write(postData);
        dos.flush();
        dos.close();
        // 判断请求是否成功
        if (urlConn.getResponseCode() == 200) {
            // 获取返回的数据
            data = IOUtils.getTextFromStream(urlConn.getInputStream());
        } else {
            ToastUtil.showShort(context,"请求失败");
        }

        return data;
    }

其中的ToastUtil是一个Toast的自定义基类:

public class ToastUtil {
    public static void showShort(Context context,String content){
        Toast.makeText(context, content, Toast.LENGTH_SHORT).show();
    }

    public static void showLong(Context context,String content){
        Toast.makeText(context, content, Toast.LENGTH_LONG).show();
    }

    public static void showShort(Context context,int contentId){
        Toast.makeText(context, contentId, Toast.LENGTH_SHORT).show();
    }

    public static void showLong(Context context,int contentId){
        Toast.makeText(context, contentId, Toast.LENGTH_LONG).show();
    }
}

IOutils为解析InputStream的一个工具类:

public class IOUtils {

    public static String getTextFromStream(InputStream inputStream){

        byte[] b = new byte[1024];
        int len = 0;
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            while ((len = inputStream.read(b))!=-1){
                byteArrayOutputStream.write(b,0,len);
            }
            String text = new String(byteArrayOutputStream.toByteArray());
            return text;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

苏王

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值