使用java发送HTTP请求

本文介绍了一种使用Java原生库java.net.URL与java.net.HttpURLConnection实现HTTP请求的方法,包括GET与POST请求,并提供了测试样例。

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

近来在写项目时调用第三方接口,发现使用第三方接口基本都要使用java程序来发送HTTP请求到第三方的服务器去获取数据,不同的第三方提供的方法不尽相同,有使用org.apache.commons.httpclient的,有使用org.apache.http.client的,有使用org.codehaus.xfire.client,还有使用org.springframework.web.client的,个人还是比较喜欢使用java原生的java.net.URL与java.net.HttpURLConnection来发送HTTP请求,所以自己写了一个方法,共飨诸君

public static String sendHttpRequest(String url, String entity, String method) {
    BufferedReader bufferedReader = null;
    URL realUrl;
    HttpURLConnection conn = null;
    PrintWriter printWriter = null;
    String result = "";
    try {
        if ("get".equals(method)) {
            if (entity != null && !"".equals(entity)) {
                realUrl = new URL(url + "?" + entity);
            } else {
                realUrl = new URL(url);
            }
            // 根据url生成urlConnection对象
            conn = (HttpURLConnection) realUrl.openConnection();
           /* conn.connect();可以不明文设定连接,conn.getInputStream()会自动连接*/
        } else if ("post".equals(method)) {
            realUrl = new URL(url);
            conn = (HttpURLConnection) realUrl.openConnection();
            conn.setRequestMethod("POST");/*设定请求的方法为"POST",默认是GET */
            if (entity != null && !"".equals(entity)) {
                // 设置是否从httpUrlConnection读入,默认情况下是true;
                conn.setDoInput(true);
                /*设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在 http正文内,因此需要设为true, 默认情况下是false*/
                conn.setDoOutput(true);
                // Post 请求不能使用缓存
                conn.setUseCaches(false);
                conn.connect();
                printWriter = new PrintWriter(conn.getOutputStream());
                printWriter.print(entity);
                printWriter.flush();
            }
        }else{
            throw new IllegalArgumentException("请输入正确的请求方式");
        }
        bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        if ((line = bufferedReader.readLine()) != null) {
            result += line;
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (printWriter != null) {
                printWriter.close();
            }
            if (bufferedReader != null) {
                bufferedReader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

}
测试方法如下:<特意测试了post请求,请求参数为null的情况>

public static void main(String[] args) {
    String str = "userMobile=15539266567&usertype=0";
    System.out.println(sendHttpRequest("http://localhost:8080/mine/try", null, "get"));
    System.out.println(sendHttpRequest("http://localhost:8080/mine/your/best", str, "post"));
    System.out.println(sendHttpRequest("http://localhost:8080/mine/so/amazing", null, "post"));
}
在控制台打印输出,哈哈,是不是很完美。关于PUT请求与DELETE请求与POST请求类似,不再敖述。

false
1
{"StageCategory":[{"id":"001","name":"第一阶段"},{"id":"002","name":"第二阶段"},{"id":"003","name":


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值