Hi, so I'm trying to create a Java program that makes use of the JIRA REST API in order to receive information about the amount of issues in a certain project. Using curl, this is easy. Using Java, I run into a 401 Unauthorized error, and I'm not entirely sure why. Can someone help? My code is below.
import java.io.*; import java.net.*; import org.apache.commons.codec.binary.Base64; public class JiraConnector { public static void main(String[] args) { HttpURLConnection connection = null; try { //store necessary query information URL jiraURL = new URL("http://jira.somecompany.com/rest/api/2/search"); String data = "{\"jql\":\"project = PROJ\"}"; byte[] dataBytes = data.getBytes("UTF-8"); String login = "user:password"; byte[] encodedBytes = Base64.encodeBase64(login.getBytes()); //establish connection and request properties connection = (HttpURLConnection) jiraURL.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Accept", "*/*"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Authorization", "Basic " + encodedBytes); connection.setUseCaches(false); connection.setDoOutput(true); connection.setDoInput(true); connection.connect(); DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.write(dataBytes); wr.flush(); wr.close(); Reader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); for (int c; (c = in.read()) >= 0; System.out.print((char)c)); } catch (MalformedURLException e) { System.err.println("MalformedURLException: " + 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) {} } } } }
Community moderators have prevented the ability to post new answers.
Update:
Found the problem. Basic authorization needed me to send a String of the encoded bytes, rather than a byte[].
Thank you so much as much as it's possible. You've just saved me hours of wondering what the hell is going on with my script. Really thanks!
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Hi Yotam,
We how some samples of OAuth providers in a number of languages, including JAVA. You may visit the sample repo on Bitbucket to download and work with these samples. You may also check this documentation for more details.
Cheers
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.