发送HTTP的POST请求调用第三方接口交互,传递必要的参数

该博客介绍了如何在项目中引入依赖,配置config.properties文件,并编写配置类来实现通过HTTP POST方法与第三方接口进行参数交互的详细步骤。

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

首先引入依赖

   <!-- okhttp3 -->
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>3.2.0</version>
        </dependency>

配置一个路径配置文件config.properties

//3.2查询账务
config.getRoomBill = http://****自己的地址
//4.1查询会员信息
config.checkIfVip = http://****

写一个配置类:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

/**
 * @Auther:
 * @Date: 2018/12/18 20:55
 * @Description:省略getset方法
 */
@Configuration
@PropertySource(value = "classpath:config/config.properties")
public class ConfigPath {
    //1.1
    @Value("${config.getRoomType}")
    private String getRoomType;
    //1.2
    @Value("${config.getRoomInfo}")

具体调用过程:

具体调用方法因人而异
String url1 = configPath.getxxx();
            JSONObject map1 = new JSONObject();
            map1.put("pmsTypeId", xxx.getxxx());
            map1.put("hotelCode", xxx.getxxx());
            map1.put("roomNo", xxx.getxxx());
            map1.put("orderCode", xxx.getxxx());
str1 = OkHttpUtil.doPostHttpRequest(url1, map1.toString());

负责发送postHTTP请求的配置:

package com.chinahotelhelp.shm.businessmanagement.tools;


import com.squareup.okhttp.*;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @Auther:
 * @Date: 2018/12/14 11:47
 * @Description:
 */
public class OkHttpUtil {
    private static final OkHttpClient client = new OkHttpClient();
    public static final MediaType JSON = MediaType
            .parse("application/json; charset=utf-8");
    private static final MediaType MEDIA_TYPE_PNG = MediaType
            .parse("image/png;charset=utf-8");
    private static final MediaType MEDIA_TYPE_MARKDOWN = MediaType
            .parse("text/x-markdown; charset=utf-8");
    static {
        client.setConnectTimeout(30, TimeUnit.SECONDS);
    }

    /**
     * 不会开启异步线程。
     *
     * @param request
     * @return
     * @throws IOException
     */
    public static Response execute(Request request) throws IOException {
        return client.newCall(request).execute();
    }

    /**
     * 开启异步线程访问网络
     *
     * @param request
     * @param responseCallback
     */
    public static void enqueue(Request request, Callback responseCallback) {
        client.newCall(request).enqueue(responseCallback);
    }

    /**
     * 根据url地址获取数据
     *
     * @param url
     * @return
     * @throws IOException
     */
    public static String doGetHttpRequest(String url) throws IOException {
        Request request = new Request.Builder().url(url).build();
        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) {

            throw new IOException("Unexpected code " + response);
        }
        return response.body().string();
    }

    /**
     * 根据url地址和json数据获取数据
     *
     * @param url
     * @param json
     * @return
     * @throws IOException
     */
    public static String doPostHttpRequest(String url, String json)
            throws IOException {
        Request request = new Request.Builder().url(url)
                .post(RequestBody.create(JSON, json)).build();

        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) {

            throw new IOException("Unexpected code " + response);
        }
        return response.body().string();
    }

    /**
     * 根据url地址和json数据获取数据
     *
     * @param url
     * @param json
     * @return
     * @throws IOException
     */
    public static String doPostHttpRequest2(String url, String json)
            throws IOException {
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, json);
        Request request = new Request.Builder().url(url).post(body)
                .addHeader("content-type", "application/json").build();

        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) {

            throw new IOException("Unexpected code " + response);
        }
        return response.body().string();
    }

    public static String doPostImgHttpRequest(String url, File file)
            throws IOException {
        RequestBody requestBody = new MultipartBuilder()
                .type(MultipartBuilder.FORM)
                .addFormDataPart("buffer", file.getName(),
                        RequestBody.create(MEDIA_TYPE_PNG, file)).build();
        Request request = new Request.Builder().url(url).post(requestBody)
                .build();
        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) {

            throw new IOException("Unexpected code " + response);
        }
        return response.body().string();
    }
}

 

 

### 如何在Java中调用第三方API 为了实现与第三方服务交互的功能,在Java应用程序中通常会采用HTTP请求的方式来进行数据交换。对于现代开发而言,`HttpURLConnection` 或者更高级别的库如 `Apache HttpClient` 和 `OkHttp` 是常用的选择之一[^1]。 下面是一个简单的例子展示怎样利用 `HttpURLConnection` 来发起GET请求并处理响应: ```java import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class ApiCaller { private static final String USER_AGENT = "Mozilla/5.0"; public static void main(String[] args) throws Exception { // 创建URL对象指向目标API地址 URL obj = new URL("https://api.example.com/data"); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // 设置必要参数 con.setRequestMethod("GET"); con.setRequestProperty("User-Agent", USER_AGENT); int responseCode = con.getResponseCode(); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // 打印结果 System.out.println(response.toString()); } } ``` 当涉及到POST方法发送JSON格式的数据时,则可以构建相应的实体内容并通过设置合适的头部信息来完成操作。这里给出一段示范代码用于说明如何执行这样的任务: ```java // ... 继续上面的例子 ... con.setDoOutput(true); // 表明此连接将被用来写入输出流 String urlParameters = "{\"key\":\"value\"}"; // JSON字符串作为参数传递给服务器端口 byte[] postDataBytes = urlParameters.getBytes("UTF-8"); con.setRequestProperty("Content-Type", "application/json"); con.setRequestProperty("charset", "utf-8"); con.setRequestProperty("Content-Length", Integer.toString(postDataBytes.length)); try(OutputStream os = con.getOutputStream()){ os.write(postDataBytes); } int responseCode = con.getResponseCode(); // 获取返回的状态码 System.out.println("POST Response Code :: " + responseCode); if (responseCode == HttpURLConnection.HTTP_OK){ try(BufferedReader br = new BufferedReader(new InputStreamReader((con.getInputStream()), "utf-8"))){ StringBuilder response = new StringBuilder(); String responseLine; while ((responseLine = br.readLine()) != null) { response.append(responseLine.trim()); } System.out.println(response.toString()); // 输出接收到的内容 } }else{ System.out.println("POST request failed."); } ``` 值得注意的是,实际应用过程中还需要考虑异常情况下的错误处理机制以及安全性方面的要求(比如HTTPS加密传输)。此外,如果所使用的API提供了SDK的话,那么直接集成官方提供的客户端可能是更为简便高效的做法。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值