简体   繁体   English

使用Java向JIRA发送HTTP POST请求会产生400错误的请求错误,curl正常运行

[英]HTTP POST request to JIRA using Java yields 400 bad request error, curl works fine

So I'm trying to retrieve information about Jira issues through REST API using Java, however I keep getting the 400 error. 因此,我试图通过使用Java的REST API检索有关Jira问题的信息,但是仍然出现400错误。 I feel like there's something really stupid that I'm missing, can anyone help me find out what's wrong with this? 我觉得我真的缺少一些愚蠢的东西,有人可以帮我找出这是怎么回事吗? EDIT: I realised that I'm not sending the username/password to Jira in the Java program, but I'm actually unsure how to do that... Help here would be great! 编辑:我意识到我没有在Java程序中将用户名/密码发送给Jira,但实际上我不确定如何执行此操作……这里的帮助将非常棒! Here is the code I have (company name edited): 这是我拥有的代码(公司名称已编辑):

import java.io.*;
import java.net.*;
import java.util.*;

public class JiraConnector 
{
    public static void main(String[] args)
    {
        try {
            //store necessary query information
            URL jiraURL = new URL("http://jira.somecompany.com/rest/api/2/search");
            String data = "'{\"jql\":\"project = PROJ\"}'";

            //establish connection and request properties
            HttpURLConnection connection = (HttpURLConnection)jiraURL.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Accept", "*/*");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setDoOutput(true);
            connection.setDoInput(true);

            connection.connect();

            OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
            wr.write(data.toString());
            wr.flush();
            wr.close();

            Reader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            for (int c; (c = in.read()) >= 0; System.out.print((char)c));

        } catch (MalformedURLException e) {
            System.err.println("MalformedURLException: " + e.getMessage());
        } catch (java.net.UnknownServiceException e) {
            System.err.println("UnknownServiceException: " + e.getMessage());
        } catch (IOException e) {
            System.err.println("IOException: " + e.getMessage());
        }        
    }
}

For the record, using this curl command works: 作为记录,使用以下curl命令有效:

curl -D- -u- user:password -X POST -H "Content-Type: application/json" --data '{"jql:"project=PROF"}' "http://jira.somecompany.com/rest/api/2/search"

A general tip first: use for instance FireFox with the TamperData add-on, which enables to trace a regular form submit, and inspect everything. 首先要提一个一般性的技巧:例如将FireFox与TamperData附加组件一起使用,从而可以跟踪常规表单提交并检查所有内容。 In your case a proxy monitor might be more of a help. 在您的情况下,代理监视器可能会更有帮助。 Also: 也:

curl --trace-ascii ...

TamperData will show where it goes wrong. TamperData将显示出问题所在。

Without encoding parameter the current platform encoding is taken; 如果没有编码参数,则采用当前平台编码。 non-portable. 不可携带。

OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream(),
        StandardCharsets.UTF_8);
Reader in = new BufferedReader(new InputStreamReader(
        connection.getInputStream(),
        StandardCharsets.UTF_8));

You seem to have extra single quotes in the post data. 您似乎在帖子数据中有多余的单引号。

Instead of this: 代替这个:

String data = "'{\"jql\":\"project = PROJ\"}'";

try this: 尝试这个:

String data = "{\"jql\":\"project = PROJ\"}";

Incidentally, even though you are getting a 400 Bad Request, JIRA is still providing useful information that helps localize the error. 顺便说一句,即使您收到400错误的请求,JIRA仍会提供有用的信息来帮助定位错误。 You can look at it using the connection's getErrorStream method. 您可以使用连接的getErrorStream方法查看它。 If we quickly slap this onto your code: 如果我们迅速将其添加到您的代码中:

import java.io.*;
import java.net.*;
import java.util.*;

public class JiraConnector 
{
    public static void main(String[] args)
    {
        HttpURLConnection connection = null;
        try {
            //store necessary query information
            URL jiraURL = new URL("http://127.0.0.1:8082/rest/api/2/search");
            String data = "{\"jql\":\"project = PROJ\"}";

            //establish connection and request properties
            connection = (HttpURLConnection)jiraURL.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Accept", "*/*");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setDoOutput(true);
            connection.setDoInput(true);

            connection.connect();

            OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
            wr.write(data.toString());
            wr.flush();
            wr.close();

            Reader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            for (int c; (c = in.read()) >= 0; System.out.print((char)c));

        } catch (MalformedURLException e) {
            System.err.println("MalformedURLException: " + e.getMessage());
        } catch (java.net.UnknownServiceException e) {
            System.err.println("UnknownServiceException: " + e.getMessage());
        } catch (IOException e) {
            System.err.println("IOException: " + e.getMessage());
            if (connection != null) {
                try {
                    System.out.println(connection.getResponseMessage());

                    InputStream errorStream = connection.getErrorStream();
                    if (errorStream != null) {
                        Reader in = new BufferedReader(new InputStreamReader(errorStream));
                        for (int c; (c = in.read()) >= 0; System.out.print((char)c));
                    }
                }
                catch (IOException e2) {
                }
            }
        }        
    }
}

If you're going to be doing any serious work against the REST API, I would recommend looking at using Jersey instead of trying to roll your own. 如果您打算针对REST API做任何认真的工作,我建议您考虑使用Jersey,而不是尝试自己动手。

Heads up, the problem was authorization (in case anyone has this problem as well). 请注意,问题出在授权(万一有人也有此问题)。 Totally derped and forgot to send username/password. 完全迷糊,忘了发送用户名/密码。

Adding a basic authorization header is easy enough: 添加基本​​授权标头很容易:

HttpURLConnection connection = (HttpURLConnection)jiraURL.openConnection();
String userCredentials = "username:password";
String basicAuth = "Basic " + new String(new Base64().encode(userCredentials.getBytes()));
connection.setRequestProperty ("Authorization", basicAuth);

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

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