使用HttpURLConnection执行cURL命令的Java返回204(HTTP_NO_CONTENT) [英] Java executing curl command using HttpURLConnection returns 204 (HTTP_NO_CONTENT)

查看:58
本文介绍了使用HttpURLConnection执行cURL命令的Java返回204(HTTP_NO_CONTENT)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是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'

返回以下内容:

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

但是,当我尝试使用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;
}

以空白响应输出以下内容:

204 Response: ''.

问题

如何使Java应用程序也返回与命令行调用相同的结果?

更新

我有一个不同的POST URL,我也需要调用它,我可以成功地调用它。所以我的Get调用有问题。

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

例如,Get调用返回204,没有内容。

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;
}

返回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;
}

所以看到POST调用起作用了,我想我一定是GET调用出了什么问题。

推荐答案

您是否尝试在您的Java代码中设置cURL将使用的相同用户代理?类似curl/7.37.0的内容? 就我所知,这应该就是所有的不同之处。在重定向之后,撇开卷曲。但由于没有重定向,我猜可能是用户代理起了作用。

有很多服务器应用程序在被浏览器调用时表现不同(就像您通过将User-Agent设置为Mozilla/5.0来使其思考一样),而不是像cURL这样的其他应用程序。

这篇关于使用HttpURLConnection执行cURL命令的Java返回204(HTTP_NO_CONTENT)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆