You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

已连接JIRA,如何在Java 8中通过REST API获取指定字段

Solution to Fetch Specific JIRA Fields Using REST API

Great news that your JIRA connection is working! Let's get you set up to fetch those specific fields using the JIRA REST API's search endpoint. Here's how to integrate this into your existing code:

Step 1: Update the fetchFields Method to Use the Search Endpoint

The JIRA REST API has a dedicated endpoint for searching issues: /rest/api/2/search. We'll send a POST request here with your JQL query and specify exactly which fields we want to retrieve to keep the response lean.

Step 2: Add JSON Parsing Support

Since the response will be in JSON format, we'll use Jackson (a popular JSON library) to deserialize the response into manageable Java objects. You'll need to add the Jackson jars to your project: jackson-databind-2.15.2.jar and jackson-core-2.15.2.jar (fully compatible with Java 8).

Updated Full Code

Here's your modified code with the field-fetching logic included:

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.core.util.Base64;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.Iterator;

public class JiraData {
    static ClientResponse response;
    // Update this to your actual JIRA instance URL
    private static final String JIRA_BASE_URL = "https://jira.com";
    private static final String SEARCH_ENDPOINT = "/rest/api/2/search";

    public static void main(String[] args) {
        try {
            String auth = new String(Base64.encode("username" + ":" + "password"));
            final String headerAuthorization = "Authorization";
            final String headerAuthorizationValue = "Basic " + auth;
            final String headerType = "application/json";

            Client c = Client.create();
            WebResource webResource = c.resource(JIRA_BASE_URL);

            // Verify connection (your existing logic)
            response = webResource.header(headerAuthorization, headerAuthorizationValue)
                    .type(headerType)
                    .accept(headerType)
                    .get(ClientResponse.class);

            String connectionresult = response.toString();
            System.out.println(connectionresult); // Returns 200 OK on success

            if (response.getResponseStatus() != null && response.getResponseStatus().getStatusCode() == 200) {
                System.out.println("Connection Successful");
                fetchFields(c, headerAuthorizationValue, headerType);
            }

        } catch(Exception e) {
            System.out.println(" Connection Error " + e);
            e.printStackTrace();
        }
    }

    private static void fetchFields(Client client, String authHeaderValue, String contentType) {
        try {
            String jql = "project = SAMPLE";
            // Define exactly which fields we want to retrieve
            String fields = "key,issuetype,status";

            // Build the JSON request body with JQL and field list
            String requestBody = String.format("{\"jql\": \"%s\", \"fields\": [\"%s\"]}", jql, fields.replace(",", "\",\""));

            WebResource searchResource = client.resource(JIRA_BASE_URL + SEARCH_ENDPOINT);

            // Send POST request to the search endpoint
            ClientResponse searchResponse = searchResource.header("Authorization", authHeaderValue)
                    .type(contentType)
                    .accept(contentType)
                    .post(ClientResponse.class, requestBody);

            if (searchResponse.getStatusCode() == 200) {
                // Parse the JSON response using Jackson
                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode rootNode = objectMapper.readTree(searchResponse.getEntityInputStream());

                // Iterate through each issue in the results
                JsonNode issuesNode = rootNode.get("issues");
                if (issuesNode != null && issuesNode.isArray()) {
                    Iterator<JsonNode> issuesIterator = issuesNode.elements();
                    while (issuesIterator.hasNext()) {
                        JsonNode issueNode = issuesIterator.next();
                        String ticketNumber = issueNode.get("key").asText();
                        String ticketUrl = JIRA_BASE_URL + "/browse/" + ticketNumber;
                        String issueType = issueNode.get("fields").get("issuetype").get("name").asText();
                        String ticketStatus = issueNode.get("fields").get("status").get("name").asText();

                        // Print the retrieved ticket details
                        System.out.println("\n--- Ticket Details ---");
                        System.out.println("Ticket Number: " + ticketNumber);
                        System.out.println("Ticket URL: " + ticketUrl);
                        System.out.println("Issue Type: " + issueType);
                        System.out.println("Ticket Status: " + ticketStatus);
                    }
                } else {
                    System.out.println("No issues found for the given JQL query.");
                }
            } else {
                System.out.println("Failed to fetch issues. Status code: " + searchResponse.getStatusCode());
                System.out.println("Response: " + searchResponse.getEntity(String.class));
            }

            // Clean up the search response
            searchResponse.close();

        } catch(Exception e) {
            System.out.println(" Error from fetchFields method " + e);
            e.printStackTrace();
        } finally {
            if (response != null) {
                response.close();
            }
        }
    }
}

Key Changes Explained:

  • Search Endpoint: We use /rest/api/2/search, the standard JIRA REST API endpoint for issue searches.
  • Targeted Field Request: We specify only the fields we need (key, issuetype, status) to keep the response small and focused.
  • JSON Parsing: Jackson's ObjectMapper helps us extract specific values from the JSON response without manual string manipulation.
  • Ticket URL Construction: We build the ticket URL using the issue key (follows JIRA's standard /browse/KEY pattern).
  • Resource Reuse: We pass the existing Client instance to fetchFields for better performance.

Alternative: Using the Official JIRA Java Client (SearchResult Class)

You mentioned the SearchResult class—this is part of the official JIRA Java Client library, not the raw Jersey approach you're currently using. If you want to switch to this method:

  1. Add the JIRA Java Client dependency (jira-rest-java-client-core-5.2.0.jar works with Java 8).
  2. Initialize a JiraRestClient with your credentials.
  3. Use the searchJql method to get a SearchResult object, then iterate over issues directly as Java objects.

Since you already have a working Jersey setup, the REST API approach above is more seamless for your current codebase. But if you want code for the official client, just let me know!

Important Notes:

  • Credentials: Replace "username" and "password" with your actual JIRA credentials. For cloud instances, use your email as the username and an API token as the password.
  • Jackson Setup: Add the Jackson jars to your Eclipse project's build path. If using Maven, add the jackson-databind dependency to your pom.xml.
  • JQL Customization: Adjust the jql string to fit your needs (e.g., "project = SAMPLE AND status != Closed").
  • Additional Fields: To fetch more fields, add them to the fields string (e.g., "key,issuetype,status,summary,assignee").

Testing this code should give you the ticket details you need. Let me know if you run into any issues with JSON parsing or API requests!

内容的提问来源于stack exchange,提问作者Vikas J

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:16:04