后台发送GET/POST方法

本文详细介绍了Java中如何发送GET和POST请求,包括通用方法以及返回JSON数据的处理。讲解了HttpURLConnection和HttpsURLConnection的使用,并给出了HTTPS请求的例子。同时推荐了几个关于JAVA利用HttpClient进行HTTP请求的博客资源。

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

前言:

1,get请求

2,post请求

3,post,get通用方法

4,其他的get,post写法

正文:

1,get请求

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;

// HTTP GET request
public static String SendGet(String url) {
    HttpClient client = new HttpClient();
    GetMethod method = new GetMethod(url);
    
    try {
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            logger.error("获取SendGet失败:" + method.getStatusLine());
        }
        
        return method.getResponseBodyAsString();
    } catch (HttpException e) {
        logger.error("获取SendGet失败: Fatal protocol violation", e);
    } catch (IOException e) {
        logger.error("获取SendGet失败: transport error", e);
    } finally {
          method.releaseConnection();
    }
    
    return "";
}

2,post请求

// HTTP POST
public static String SendPOST(String url) {
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(url);
    
    try {
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            logger.error("获取SendPOST失败:" + method.getStatusLine());
        }
        
        return method.getResponseBodyAsString();
    } catch (HttpException e) {
        logger.error("获取SendPOST失败: Fatal protocol violation", e);
    } catch (IOException e) {
        logger.error("获取SendPOST失败: transport error", e);
    } finally {
          method.releaseConnection();
    }
    
    return "";
}

3,post,get通用方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值