Java中用JSON方式请求第三方接口工具类

doGetPost1("url","get请求或者post请求")


public String doGetPost1(String apiPath,String type){
        OutputStreamWriter out = null;
        InputStream is = null;
        String result = null;
        try{
            URL url = new URL(apiPath);// 创建连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod(type) ; // 设置请求方式
            connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
            connection.connect();
            if(type.equals("POST")){
                out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
                out.append(JSON.toJSONString(paramMap));  如果是post请求,携带的参数
                out.flush();
                out.close();
            }
            // 读取响应
            is = connection.getInputStream();
            int length = (int) connection.getContentLength();// 获取长度
            if (length != -1) {
                byte[] data = new byte[length];
                byte[] temp = new byte[512];
                int readLen = 0;
                int destPos = 0;
                while ((readLen = is.read(temp)) > 0) {
                    System.arraycopy(temp, 0, data, destPos, readLen);
                    destPos += readLen;
                }
                result = new String(data, "UTF-8"); // utf-8编码
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return  result;
    }

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java调用第三方接口需要使用 Java 提供的网络请求 API,通常有两种方式: 1. 使用 HttpURLConnection 类发送 HTTP 请求 HttpURLConnection 是 Java 中用于发送 HTTP 请求的类,可以使用此类发送 GET、POST、PUT、DELETE 等请求。具体步骤如下: ```java // 创建 URL 对象 URL url = new URL("http://example.com/api"); // 打开连接 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 设置请求方法 conn.setRequestMethod("GET"); // 设置请求头 conn.setRequestProperty("Content-Type", "application/json"); // 发送请求 conn.connect(); // 获取响应码 int responseCode = conn.getResponseCode(); // 获取响应数据 InputStream inputStream = conn.getInputStream(); // 读取响应数据 BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); inputStream.close(); // 关闭连接 conn.disconnect(); // 处理响应数据 System.out.println(response.toString()); ``` 2. 使用 HttpClient 库发送 HTTP 请求 HttpClient 是 Apache 提供的开源 HTTP 客户端库,可以用于发送 HTTP 请求,支持 GET、POST、PUT、DELETE 等请求。具体步骤如下: ```java // 创建 HttpClient 对象 CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建 HttpGet 或 HttpPost 对象 HttpGet httpGet = new HttpGet("http://example.com/api"); // 设置请求头 httpGet.setHeader("Content-Type", "application/json"); // 发送请求 CloseableHttpResponse response = httpClient.execute(httpGet); // 获取响应数据 HttpEntity entity = response.getEntity(); String result = EntityUtils.toString(entity, "UTF-8"); // 关闭响应和连接 response.close(); httpClient.close(); // 处理响应数据 System.out.println(result); ``` 需要注意的是,在调用第三方接口时,需要遵循接口提供方的协议和规范,如授权、请求频率等限制。同时,为了保证数据安全,建议将敏感信息加密传输。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值