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

如何用Java调用Instagram API获取评论?学生作业技术问询

How to Fetch Instagram Comments via Instagram API in Java

Hey there! I get that you're working on a school assignment where you need to pull Instagram comments for SentiStrength analysis, and you're stuck on making GET requests in Java (plus you don't want to mess with Python). Let's walk through this step by step to get you up and running.

First: Get Set Up with Instagram Graph API

Before writing any code, you need to sort out API access—Instagram uses the Instagram Graph API (tied to Facebook's developer platform), so here's what you need to do:

  • Create a Facebook Developer account and register a new app.
  • Link your Instagram account to the app (if it's a personal account, you'll need to convert it to a Creator or Business account first).
  • Request the necessary permissions: instagram_basic, pages_read_engagement, and pages_show_list (these are required to access media and comments).
  • Generate a short-lived access token, then exchange it for a long-lived one (so you don't have to refresh it constantly for your assignment).

Option 1: Use Java's Built-in HttpURLConnection (No External Libraries)

If you want to stick to plain Java without adding dependencies, HttpURLConnection works perfectly. Here's a complete example to fetch comments for a specific Instagram media post:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONArray;
import org.json.JSONObject;

public class InstagramCommentFetcher {
    public static void main(String[] args) {
        // Replace these with your actual values
        String mediaId = "YOUR_MEDIA_ID"; // Get this from your media's Instagram URL or API
        String accessToken = "YOUR_LONG_LIVED_ACCESS_TOKEN";
        
        try {
            // Build the API endpoint URL
            String apiUrl = "https://graph.instagram.com/" + mediaId + "/comments?fields=id,text,timestamp&access_token=" + accessToken;
            URL url = new URL(apiUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            
            // Read the response
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            conn.disconnect();
            
            // Parse the JSON response to extract comments
            JSONObject jsonResponse = new JSONObject(response.toString());
            JSONArray comments = jsonResponse.getJSONArray("data");
            
            // Loop through comments and print the text (you'll pass this to SentiStrength)
            for (int i = 0; i < comments.length(); i++) {
                JSONObject comment = comments.getJSONObject(i);
                String commentText = comment.getString("text");
                System.out.println("Comment: " + commentText);
                // Now you can send commentText to SentiStrength for analysis
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Note: You'll need to include the org.json library in your project to parse JSON—most IDEs let you add this via Maven/Gradle or download the JAR directly.

Option 2: Use OkHttp (Simpler, External Library)

If you don't mind adding a lightweight library, OkHttp makes HTTP requests way cleaner. Here's how to do it with OkHttp:

First, add the dependency (if using Maven):

<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.11.0</version>
</dependency>

Then the code:

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.json.JSONArray;
import org.json.JSONObject;

public class InstagramCommentFetcherOkHttp {
    public static void main(String[] args) {
        String mediaId = "YOUR_MEDIA_ID";
        String accessToken = "YOUR_LONG_LIVED_ACCESS_TOKEN";
        OkHttpClient client = new OkHttpClient();
        
        String apiUrl = "https://graph.instagram.com/" + mediaId + "/comments?fields=id,text,timestamp&access_token=" + accessToken;
        Request request = new Request.Builder().url(apiUrl).get().build();
        
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new RuntimeException("Unexpected code " + response);
            
            String responseBody = response.body().string();
            JSONObject jsonResponse = new JSONObject(responseBody);
            JSONArray comments = jsonResponse.getJSONArray("data");
            
            for (int i = 0; i < comments.length(); i++) {
                String commentText = comments.getJSONObject(i).getString("text");
                System.out.println("Comment: " + commentText);
                // Pass commentText to SentiStrength here
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Key Notes for Your Assignment

  • Finding the Media ID: You can get the ID of your Instagram post by calling the /{instagram-account-id}/media endpoint first, which returns all your media and their IDs.
  • SentiStrength Integration: Once you have the comment text, you can call SentiStrength's Java API (it usually has a method like getSentimentScore(String text)—check their documentation for exact usage).
  • Rate Limits: Instagram API has rate limits, so don't spam requests if you're testing with a lot of posts.
  • Token Expiry: Long-lived tokens last 60 days, which should be enough for a school assignment, but keep an eye on it if you're working over a longer period.

内容的提问来源于stack exchange,提问作者Jamil Ahmed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 09:11:02