Java Program to fetch custom/default fields of iss

2020-05-03 10:57发布

I have developed a simple java program to fetch the data of issues/user stories. I want to fetch 'description' field of a perticular issue. I have used GET method to get response but I'm getting errors while connecting to JIRA.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class JiraIssueDescription {

public static void main(String[] args) {

  try {

    URL url = new URL("https://****.atlassian.net/rest/agile/1.0/issue/41459");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setRequestProperty("Accept", "application/json");
    conn.setRequestProperty("username", "***@abc.com");
    conn.setRequestProperty("password", "****");

    if (conn.getResponseCode() != 200) {
        throw new RuntimeException("Failed : HTTP error code : "
                + conn.getResponseCode());
    }

    BufferedReader br = new BufferedReader(new InputStreamReader(
        (conn.getInputStream())));

    String output;
    System.out.println("Output from Server .... \n");
    while ((output = br.readLine()) != null) {
        System.out.println(output);
    }

    conn.disconnect();

  } catch (MalformedURLException e) {

    e.printStackTrace();

  } catch (IOException e) {

    e.printStackTrace();

  }

}

}

When I run the project I get following error

java.net.UnknownHostException: ****.atlassian.net
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.security.ssl.SSLSocketImpl.connect(Unknown Source)
at sun.security.ssl.BaseSSLSocketImpl.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.<init>(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.New(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.HttpURLConnection.getResponseCode(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(Unknown Source)
at com.JiraIntegration.bean.JiraIssueDescription.main(JiraIssueDescription.java:24)

Can anyone please help me with the errors. Do I need to implement OAuth ?

2条回答
贼婆χ
2楼-- · 2020-05-03 11:35

UnknownHostException looks like you have a typo in your URL or are facing some proxy issues .

  1. Does it work in your Browser? It should give you some json in response. Like this: https://jira.atlassian.com/rest/api/2/issue/JSWCLOUD-11658

  2. You could also test with other tools like curl. Does it work? curl https://jira.atlassian.com/rest/api/2/issue/JSWCLOUD-11658

  3. Atlassian rest API provides two authentication methods, Basic auth and Oauth. Use this approach to create a valid basic auth header or try the request without parameters.

The following code demonstrates how it should work:

package stack48618849;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

import org.junit.Test;

public class HowToReadFromAnURL {
    @Test
    public void readFromUrl() {
        try (InputStream in = getInputStreamFromUrl("https://jira.atlassian.com/rest/api/2/issue/JSWCLOUD-11658")) {
            System.out.println(convertInputStreamToString(in));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Test(expected = RuntimeException.class)
    public void readFromUrlWithBasicAuth() {
        String user="aUser";
        String passwd="aPasswd";
        try (InputStream in = getInputStreamFromUrl("https://jira.atlassian.com/rest/api/2/issue/JSWCLOUD-11658",user,passwd)) {
            System.out.println(convertInputStreamToString(in));
        } catch (Exception e) {
            System.out.println("If basic auth is provided, it should be correct: "+e.getMessage());
            throw new RuntimeException(e);
        }
    }

    private InputStream getInputStreamFromUrl(String urlString,String user, String passwd) throws IOException {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");
        String encoded = Base64.getEncoder().encodeToString((user+":"+passwd).getBytes(StandardCharsets.UTF_8));  
        conn.setRequestProperty("Authorization", "Basic "+encoded);
        return conn.getInputStream();
    }

    private InputStream getInputStreamFromUrl(String urlString) throws IOException {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");
        return conn.getInputStream();
    }

    private String convertInputStreamToString(InputStream inputStream) throws IOException {
        ByteArrayOutputStream result = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) != -1) {
            result.write(buffer, 0, length);
        }
        return result.toString("UTF-8");
    }
}

This prints:

{"expand":"renderedFields,names,schema,operations,editmeta,changelog,versionedRepresentations","id":"789521","self":"https://jira.atlassian.com/rest/api/2/issue/789521","key":"JSWCLOUD-11658","fields":{"customfield_18232":...
If basic auth is provided, it should be correct: Server returned HTTP response code: 401 for URL: https://jira.atlassian.com/rest/api/2/issue/JSWCLOUD-11658
查看更多
贪生不怕死
3楼-- · 2020-05-03 11:41

Instead of a HttpURLConnection way of implementing, you could use Spring's RestTemplate in an efficient manner to solve your problem:

Providing you a piece of code that I use, with the JIRA REST APIs:

Create a RESTClient that you would want to use in conjunction with JIRA REST APIs as like the below:

public class JIRASpringRESTClient {

    private static final String username = "fred";
    private static final String password = "fred";
    private static final String jiraBaseURL = "https://jira.xxx.com/rest/api/2/";

    private RestTemplate restTemplate;
    private HttpHeaders httpHeaders;

    public JIRASpringRESTClient() {
        restTemplate = new RestTemplate();
        httpHeaders = createHeadersWithAuthentication();
    }

    private HttpHeaders createHeadersWithAuthentication() {
        String plainCredentials = username + ":" + password;
        byte[] base64CredentialsBytes = Base64.getEncoder().encode(plainCredentials.getBytes());
        String base64Credentials = new String(base64CredentialsBytes);

        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Basic " + base64Credentials);
        return headers;
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public ResponseEntity<String> getJIRATicket(String issueId) {
        String url = jiraBaseURL + "issue/" + issueId;

        HttpEntity<?> requestEntity = new HttpEntity(httpHeaders);
        return restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
    }
}

Then you can further re-use these methods as like the below:

public class JIRATicketGet {
    public static void main(String... args) {
        JIRASpringRESTClient restClient = new JIRASpringRESTClient();
        ResponseEntity<String> response = restClient.getJIRATicket("XXX-12345");
        System.out.println(response.getBody());
    }
}

This will provide the GET response from JIRA, which is in JSON format which can be further manipulated to get the specific field from the GET response with the use of com.fasterxml.jackson.databind.ObjectMapper

Using the JSON that you get in the step above, you can create a POJO class (for example, Ticket) and then use it as follows:

ObjectMapper mapper = new ObjectMapper();
try {
    Ticket response = mapper.readValue(response.getBody(), Ticket.class);
} catch (IOException e) {
    e.printStackTrace();
}

Hope this helps!

查看更多
登录 后发表回答