【Java】 # 使用java语言在代码中调用http接口(get和post请求)

之前都是使用 ajax 请求接口,现在记录一下使用 java 请求接口的方法

使用 HttpURLConnection

简介:在 java.net 包下,提供访问 HTTP协议 的基本功能类。

1. GET 方式调用

private static void httpURLGETCase() {
    String methodUrl = "请求的http接口地址";
    HttpURLConnection connection = null;
    BufferedReader reader = null;
    String line = null;
    try {
        URL url = new URL(methodUrl + "?name=张三"); // 参数
        // 根据URL生成HttpURLConnection
        connection = (HttpURLConnection) url.openConnection();
        // 默认GET请求
        connection.setRequestMethod("GET");
        // 建立TCP连接
        connection.connect();
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            // 发送http请求
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            StringBuilder result = new StringBuilder();
            // 循环读取流
            while ((line = reader.readLine()) != null) {
                result.append(line).append(System.getProperty("line.separator"));
            }
            String s = result.toString();
            System.out.println(s); // 获取的数据
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        connection.disconnect();
    }
}

2. POST方式调用

2.1 带授权的  传递json格式参数调用

参数如果是 List 或者 Map,可以使用 JSON.toJSONString() 格式化

private static void httpURLPOSTCase() {
    String methodUrl = "http://xxx";
    HttpURLConnection connection = null;
    OutputStream dataout = null;
    BufferedReader reader = null;
    String line = null;
    try {
        URL url = new URL(methodUrl);
        
        // 根据URL生成HttpURLConnection
        connection = (HttpURLConnection) url.openConnection();
        
        // 设置是否向connection输出,默认false,post请求参数要放在http正文内,需要设为true
        connection.setDoOutput(true);
        
        // 设置是否从connection读入,默认情况下是true;
        connection.setDoInput(true); 
        
        // 设置请求方式为post,默认GET请求
        connection.setRequestMethod("POST");
        
        // post请求不能使用缓存设为false
        connection.setUseCaches(false);
        
        // 连接主机的超时时间
        connection.setConnectTimeout(3000);
        
        // 从主机读取数据的超时时间
        connection.setReadTimeout(3000);
        
        // 设置该HttpURLConnection实例是否自动执行重定向
        connection.setInstanceFollowRedirects(true);
        
        // 连接复用
        connection.setRequestProperty("connection", "Keep-Alive");
        connection.setRequestProperty("charset", "utf-8");
        connection.setRequestProperty("Content-Type", "application/json");
        // 授权
        connection.setRequestProperty("Authorization", "Bearer 66cb225f1c3ff0ddfdae31rae2b57488aadfb8b5e7");
        // 建立TCP连接,getOutputStream会隐含的进行connect,所以此处可以不要
        connection.connect();
        
        // 创建输入输出流,用于往连接里面输出携带的参数
        dataout = new DataOutputStream(connection.getOutputStream());
        String body = "[{\"id\":\"44921902\",\"name\":\"张三\"}]";
        dataout.write(body.getBytes());
        dataout.flush();
        dataout.close();

        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            // 发送http请求
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            StringBuilder result = new StringBuilder();
            // 循环读取流
            while ((line = reader.readLine()) != null) {
                result.append(line).append(System.getProperty("line.separator"));//
            }
            System.out.println(result.toString());
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        connection.disconnect();
    }
}

2.2 传递键值对

private static void httpURLPOSTCase() {
    String methodUrl = "http://xxx. ";
    try {
        URL url = new URL(methodUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.connect();

        String body = "userName=zhangsan&password=123456";
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
        writer.write(body);
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
好的,下面是 Java 调用 HTTP 接口的 PUT 请求代码示例和注释,希望能帮到您: ```java import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.Map; public class HttpUtil { /** * 发送 PUT 请求 * * @param url 请求的 URL 地址 * @param params 请求的参数,格式为 Map<String, String> * @return String * @throws Exception */ public static String sendPut(String url, Map<String, String> params) throws Exception { URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // 设置请求方法为 PUT con.setRequestMethod("PUT"); // 设置请求头部分参数 con.setRequestProperty("User-Agent", "Mozilla/5.0"); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); // 发送 PUT 请求 con.setDoOutput(true); StringBuilder postData = new StringBuilder(); for (Map.Entry<String, String> param : params.entrySet()) { if (postData.length() != 0) { postData.append('&'); } postData.append(param.getKey()); postData.append('='); postData.append(param.getValue()); } byte[] postDataBytes = postData.toString().getBytes("UTF-8"); con.getOutputStream().write(postDataBytes); // 获取响应结果 BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); return response.toString(); } } ``` 注意事项: 1. 该代码是通过 HttpURLConnection 实现的 PUT 请求,可以根据需求选择其他方式实现。 2. 参数 params 是请求的参数,以 Map<String, String> 的形式传入。 3. 代码实现了设置请求头的功能,可以根据需求添加或修改请求头的参数。 4. 在发送 PUT 请求时,需要将请求参数写入到请求。 5. 代码获取响应结果的方式是通过 BufferedReader 读取响应结果,可以根据需求使用其他方法获取响应结果。 6. 该代码仅供参考,由于每个项目的具体需求不同,可能需要根据实际情况进行修改和完善。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

LRcoding

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

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

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

打赏作者

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

抵扣说明:

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

余额充值