简体   繁体   English

Java 使用 HttpURLConnection 执行 curl 命令返回 204 (HTTP_NO_CONTENT)

[英]Java executing curl command using HttpURLConnection returns 204 (HTTP_NO_CONTENT)

I am using Java 11. I have the the following curl command, when I execute on the command line:我正在使用 Java 11。当我在命令行上执行时,我有以下 curl 命令:

curl --location --request GET 'http://xxx.xxx.co.za:8080/document/details/Select+docId+From+%27Workflow+Club%2FCustomer+Invoices%27+where+recursive+%3D+true+and+invoice_number+%3D%271221669023%27' --header 'Authorization: Basic xxx'

Returns the following:返回以下内容:

{errorMessage: 'PaperTrail API only available in enterprise edition'}

However, when I try execute the same URL in a Java application using HttpURLConnection , it returns a blank response.但是,当我尝试使用HttpURLConnection在 Java 应用程序中执行相同的 URL 时,它返回一个空白响应。

private static final String USER_AGENT = "Mozilla/5.0";

private static final String GET_URL = "http://xxx.xxx.co.za:8080/document/details/";
private static final String GET_URL_QRY = "Select docId From 'Workflow Club/Customer Invoices' where recursive = true and invoice_number =':1'";
private static final String GET_AUTH_ENC = "Basic xxx";

@Override
public String getDocId(Long invoiceNumber) {
    String get_url_qry = StringUtils.replace(GET_URL_QRY, ":1", Long.toString(invoiceNumber));
    get_url_qry = URLEncoder.encode(get_url_qry, StandardCharsets.UTF_8);
    final String get_url = GET_URL+get_url_qry;
    try {
        URL url = new URL(get_url);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestProperty("Authorization", GET_AUTH_ENC);
        con.setRequestMethod("GET");
        con.setRequestProperty("User-Agent", USER_AGENT);
        int responseCode = con.getResponseCode();
        logger.info(get_url+" -> GET Response Code :: " + responseCode);
        if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) { // 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();
            String resp = response.toString();
            logger.info(responseCode+" Response: '"+resp+"'.");
        } else {
            logger.error("GET request did not work (responseCode: "+responseCode+").");
        }
    } catch (MalformedURLException e) {
        logger.error("MalformedURLException creating URL '"+get_url+"'. "+e.getMessage());
    } catch (IOException e) {
        logger.error("IOException creating connection from URL '"+get_url+"'. "+e.getMessage());
    }
    return null;
}

Outputs the following with a blank response:以空白响应输出以下内容:

204 Response: ''.

Question问题

How do I get the Java application to also return the same as the command line call?如何让 Java 应用程序也返回与命令行调用相同的内容?

UPDATE更新

I have a different POST url, that I need to call too, and I can call it successfully.我有一个不同的POST url,我也需要调用它,我可以成功调用它。 So there's something wrong with my GET call.所以我的 GET 调用有问题。

private static final String USER_AGENT = "Mozilla/5.0";

Eg GET call that returns a 204, with no content.例如,返回 204 的 GET 调用,没有内容。

private String getDocId(Long invoiceNumber) {
    String get_url_qry = StringUtils.replace(GET_URL_QRY, ":1", Long.toString(invoiceNumber));
    get_url_qry = URLEncoder.encode(get_url_qry, StandardCharsets.UTF_8);
    final String get_url = GET_URL+get_url_qry;
    try {
        URL url = new URL(get_url);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestProperty("Authorization", GET_AUTH_ENC);
        con.setRequestMethod("GET");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        Map<String,String> data = handleResponse(con);
        return data.get("docId");
    } catch (MalformedURLException e) {
        logger.error("MalformedURLException creating URL '"+get_url+"'. "+e.getMessage());
    } catch (IOException e) {
        logger.error("IOException creating connection from URL '"+get_url+"'. "+e.getMessage());
    }
    return null;
}

The POST call, that returns a 200, and the expected content.返回 200 和预期内容的 POST 调用。

private String getDocLink(String docId) {
    if (StringUtils.isNotBlank(docId)) {
        try {
            URL url = new URL(POST_URL);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestProperty("Authorization", GET_AUTH_ENC);
            con.setRequestMethod("POST");
            con.setRequestProperty("User-Agent", USER_AGENT);
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            byte[] postDataBytes = getPostData(docId);
            con.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
            con.setDoOutput(true);
            con.getOutputStream().write(postDataBytes);
            Map<String,String> data = handleResponse(con);
            return data.get("url");
        } catch (IOException e) {
            logger.error("IOException creating connection from URL '"+POST_URL+"'. "+e.getMessage());
        }
    } else {
        logger.error("No docId provided when trying to get a document link.");
    }
    return null;
}

So seeing the that POST call works, I think I must be doing something wrong with the GET call.所以看到 POST 调用有效,我想我一定是对 GET 调用做错了。

Did you try, setting the same user agent in your Java Code, cURL would use?您是否尝试过,在您的 Java 代码中设置相同的用户代理,cURL 会使用? something like curl/7.37.0 ?curl/7.37.0这样的东西? As far as I can tell, that should be all, what differs.据我所知,这应该是全部,有什么不同。 Aside cURL following redirects.除了 cURL 之外的重定向。 But as there is no redirect, I guess it might be the User Agent making a difference.但由于没有重定向,我想可能是用户代理有所作为。

There are a lot of server applications, behaving differently, when they are called by a browser (Like you make it think by setting the User-Agent to Mozilla/5.0 ), instead of some other application, like cURL.有很多服务器应用程序在被浏览器调用时表现不同(就像您通过将 User-Agent 设置为Mozilla/5.0来想象的那样),而不是其他一些应用程序,例如 cURL。

From what you describe, the original call produces an error.根据您的描述,原始调用会产生错误。

Assuming that you are also getting some form of error in the java code of your GET, you will catch the exception and simply log it.假设您在 GET 的 java 代码中也遇到某种形式的错误,您将捕获异常并简单地记录它。 Then you will return null instead of a string, which will cause your response to have no content, ie 204.然后你将返回null而不是一个字符串,这将导致你的响应没有内容,即 204。

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

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