有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Spring引导REST获取HTTPConnectionURL的参数

我有一个SpringBoot应用程序,在其中我得到streamName作为参数,但现在我不希望它在postman中工作,而是在另一个程序中工作,其中streamName是调用函数时创建的字符串。以前我是以json的形式给出它的,但现在我想以参数的形式给出它,我不知道该怎么做

这是我在Spring boot中的请求:

@PostMapping
@ResponseBody
public String addStream(@RequestParam("streamName") String streamName) {

    String key = getRandomHexString();
    streamService.addStream(new Stream(streamName,key));
    return key;
}

这是在另一个程序中,我想用这个方法:

public void onHTTPPostRequest(String streamName) throws IOException {

    PostResponse postResponse = new PostResponse();
    postResponse.setStreamName(streamName);
    Gson gson = new Gson();
    String jsonString = gson.toJson(postResponse);

    getLogger().info("POST Body  " + jsonString);

    URL pipedreamURL = new URL("http://10.100.2.44:8080/api?streamName=");
    HttpURLConnection conn = (HttpURLConnection) pipedreamURL.openConnection();

    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json; utf-8");
    conn.setRequestProperty("Accept", "application/json");
    OutputStream os = conn.getOutputStream();
    os.write(jsonString.getBytes("UTF-8"));
    os.close();

    int responseCode = conn.getResponseCode();
    getLogger().info(responseCode);
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

共 (1) 个答案

  1. # 1 楼答案

    只需将其添加到URL字符串:

    URL pipedreamURL = new URL("http://10.100.2.44:8080/api?streamName=" + streamName);