简体   繁体   English

在 java 中调用没有正文的 Post 请求

[英]Calling Post request without body in java

I have a post API which doesn't accept any input.我有一个帖子 API 不接受任何输入。 I have to get output from API.我必须从 API 得到 output。 But it is giving compilation error.但它给出了编译错误。

HttpURLConnection connection = null;
String targetUrl="https://idcs-oda-9417f93560b94eb8a2e2a4c9aac9a3ff-t0.data.digitalassistant.oci.oc-test.com/api/v1/bots/"+BotID+"/dynamicEntities/"+dynamicEntityId+"/pushRequests
URL url = new URL(targetUrl);
connection=(HttpURLConnection) url.openConnection();
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
connection.setRequestProperty("Authorization", "Basic aWRjcy1vZGEtOTQxN2Y5MzU2MGI5NGViOGEyZTJhNGM5YWFjOWEzZmYtdDBfQVBQSUQ6MjQ0YWU4ZTItNmY3MS00YWYyLWI1Y2MtOTExMDg5MGQxNDU2");
connection.setRequestProperty("Accept", "application/json");
OutputStream os = connection.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");    
**osw.write();**   //this line is expecting input in parameter
osw.flush();
osw.close();
os.close(); 
connection.connect();

If I dont pass any value in osw.write() it gives compilation error.如果我没有在osw.write()中传递任何值,则会出现编译错误。 How can I resolve the same.我该如何解决。

Look at the following method for the post call.看下面的post调用方法。 You will need to add the outputstream to the osw.write() as it expects a parameter.您需要将输出流添加到osw.write()因为它需要一个参数。

private static void sendPOST() throws IOException {
    URL obj = new URL(POST_URL);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);

    // For POST only - START
    con.setDoOutput(true);
    OutputStream os = con.getOutputStream();
    os.write(POST_PARAMS.getBytes());
    os.flush();
    os.close();
    // For POST only - END

    int responseCode = con.getResponseCode();
    System.out.println("POST Response Code :: " + responseCode);

    if (responseCode == HttpURLConnection.HTTP_OK) { //success
        BufferedReader in = new BufferedReader(new InputStreamReader(
                    con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        // print result
        System.out.println(response.toString());
        } 
    else {
        System.out.println("POST request not worked");
    }
}

For more details on the above code look here .有关上述代码的更多详细信息,请参见此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM