0
# Twitter4J Core
1
2
Twitter4J Core is a 100% pure Java library that provides comprehensive access to the Twitter API v1.1 with no external dependencies. It offers a clean, object-oriented interface for all Twitter functionality including tweeting, timeline access, user management, search, streaming, and more.
3
4
## Package Information
5
6
- **Package Name**: twitter4j-core
7
- **Package Type**: maven
8
- **Language**: Java
9
- **Installation**:
10
```xml
11
<dependency>
12
<groupId>org.twitter4j</groupId>
13
<artifactId>twitter4j-core</artifactId>
14
<version>4.1.2</version>
15
</dependency>
16
```
17
- **Gradle**: `implementation 'org.twitter4j:twitter4j-core:4.1.2'`
18
- **Java Version**: Java 8+
19
20
## Core Imports
21
22
```java
23
import org.twitter4j.*;
24
import org.twitter4j.v1.*;
25
```
26
27
## Basic Usage
28
29
```java
30
import org.twitter4j.*;
31
32
public class TwitterExample {
33
public static void main(String[] args) throws TwitterException {
34
// Configuration via properties file (twitter4j.properties)
35
Twitter twitter = Twitter.getInstance();
36
37
// Or programmatic configuration
38
Twitter twitter = Twitter.newBuilder()
39
.oAuthConsumer("consumer key", "consumer secret")
40
.oAuthAccessToken("access token", "access token secret")
41
.build();
42
43
// Access Twitter API v1.1
44
TwitterV1 v1 = twitter.v1();
45
46
// Post a tweet
47
Status status = v1.tweets().updateStatus("Hello Twitter API!");
48
System.out.println("Posted: " + status.getText());
49
50
// Get home timeline
51
ResponseList<Status> timeline = v1.timelines().getHomeTimeline();
52
for (Status tweet : timeline) {
53
System.out.println(tweet.getUser().getName() + ": " + tweet.getText());
54
}
55
}
56
}
57
```
58
59
## Architecture
60
61
Twitter4J Core is built around several key architectural patterns:
62
63
- **Factory Pattern**: Main entry through `Twitter.getInstance()` and `Twitter.newBuilder()`
64
- **Interface-Implementation Separation**: Public APIs defined as interfaces, implementations are package-private
65
- **Resource Organization**: Twitter API v1.1 functionality grouped into logical resource interfaces
66
- **Builder Pattern**: Configuration and request building with type-safe builders
67
- **Authentication Framework**: Pluggable authentication with OAuth 1.0a and OAuth 2.0 support
68
- **Rate Limit Awareness**: Built-in rate limiting information and monitoring
69
- **Streaming Support**: Real-time data processing with listener patterns
70
71
## Capabilities
72
73
### Core Configuration and Authentication
74
75
Primary entry points and authentication management for Twitter API access.
76
77
```java { .api }
78
interface Twitter {
79
static Twitter getInstance();
80
static TwitterBuilder newBuilder();
81
TwitterV1 v1();
82
}
83
84
class TwitterBuilder {
85
TwitterBuilder oAuthConsumer(String consumerKey, String consumerSecret);
86
TwitterBuilder oAuthAccessToken(String accessToken, String accessTokenSecret);
87
TwitterBuilder oAuth2AccessToken(String oauth2AccessToken);
88
Twitter build();
89
}
90
```
91
92
[Core Configuration and Authentication](./core-auth.md)
93
94
### Tweet Operations
95
96
Complete tweet lifecycle management including posting, retrieving, deleting, and retweeting.
97
98
```java { .api }
99
interface TweetsResources {
100
Status updateStatus(String status) throws TwitterException;
101
Status updateStatus(StatusUpdate statusUpdate) throws TwitterException;
102
Status destroyStatus(long statusId) throws TwitterException;
103
Status retweetStatus(long statusId) throws TwitterException;
104
Status showStatus(long id) throws TwitterException;
105
}
106
```
107
108
[Tweet Operations](./tweets.md)
109
110
### Timeline Access
111
112
Access to various Twitter timelines including home timeline, user timeline, and mentions.
113
114
```java { .api }
115
interface TimelinesResources {
116
ResponseList<Status> getHomeTimeline() throws TwitterException;
117
ResponseList<Status> getHomeTimeline(Paging paging) throws TwitterException;
118
ResponseList<Status> getUserTimeline() throws TwitterException;
119
ResponseList<Status> getUserTimeline(String screenName, Paging paging) throws TwitterException;
120
ResponseList<Status> getMentionsTimeline() throws TwitterException;
121
}
122
```
123
124
[Timeline Access](./timelines.md)
125
126
### User Management
127
128
User profile access, lookup, search, and relationship management.
129
130
```java { .api }
131
interface UsersResources {
132
User showUser(String screenName) throws TwitterException;
133
User showUser(long userId) throws TwitterException;
134
ResponseList<User> searchUsers(String query, int page) throws TwitterException;
135
ResponseList<User> lookupUsers(String[] screenNames) throws TwitterException;
136
ResponseList<User> lookupUsers(long[] ids) throws TwitterException;
137
}
138
139
interface FriendsFollowersResources {
140
User createFriendship(String screenName) throws TwitterException;
141
User destroyFriendship(String screenName) throws TwitterException;
142
IDs getFriendsIDs(String screenName, long cursor) throws TwitterException;
143
IDs getFollowersIDs(String screenName, long cursor) throws TwitterException;
144
}
145
```
146
147
[User Management](./users.md)
148
149
### Search Functionality
150
151
Comprehensive search capabilities for tweets, users, and trending topics.
152
153
```java { .api }
154
interface SearchResource {
155
QueryResult search(Query query) throws TwitterException;
156
}
157
158
interface TrendsResources {
159
Trends getPlaceTrends(int woeid) throws TwitterException;
160
ResponseList<Location> getAvailableTrends() throws TwitterException;
161
ResponseList<Location> getClosestTrends(GeoLocation location) throws TwitterException;
162
}
163
```
164
165
[Search Functionality](./search.md)
166
167
### Direct Messages
168
169
Private messaging functionality for sending and receiving direct messages.
170
171
```java { .api }
172
interface DirectMessagesResources {
173
DirectMessage sendDirectMessage(String screenName, String text) throws TwitterException;
174
DirectMessage sendDirectMessage(long userId, String text) throws TwitterException;
175
ResponseList<DirectMessage> getDirectMessages() throws TwitterException;
176
ResponseList<DirectMessage> getSentDirectMessages() throws TwitterException;
177
DirectMessage destroyDirectMessage(long id) throws TwitterException;
178
}
179
```
180
181
[Direct Messages](./direct-messages.md)
182
183
### Lists Management
184
185
Twitter list creation, management, and member operations.
186
187
```java { .api }
188
interface ListsResources {
189
UserList createUserList(String listName, boolean isPublicList, String description) throws TwitterException;
190
UserList updateUserList(long listId, String newListName, boolean isPublicList, String newDescription) throws TwitterException;
191
ResponseList<UserList> getUserLists(String screenName) throws TwitterException;
192
ResponseList<Status> getUserListStatuses(long listId, Paging paging) throws TwitterException;
193
UserList addUserListMember(long listId, long userId) throws TwitterException;
194
UserList deleteUserListMember(long listId, long userId) throws TwitterException;
195
}
196
```
197
198
[Lists Management](./lists.md)
199
200
### Favorites and Likes
201
202
Managing tweet favorites (likes) and retrieving favorite lists.
203
204
```java { .api }
205
interface FavoritesResources {
206
Status createFavorite(long id) throws TwitterException;
207
Status destroyFavorite(long id) throws TwitterException;
208
ResponseList<Status> getFavorites() throws TwitterException;
209
ResponseList<Status> getFavorites(String screenName) throws TwitterException;
210
ResponseList<Status> getFavorites(String screenName, Paging paging) throws TwitterException;
211
}
212
```
213
214
[Favorites and Likes](./favorites.md)
215
216
### Real-time Streaming
217
218
Real-time Twitter data streaming with customizable filters and listeners.
219
220
```java { .api }
221
interface TwitterStream {
222
void addListener(StreamListener listener);
223
void filter(FilterQuery query);
224
void sample();
225
void firehose();
226
void user();
227
void cleanUp();
228
void shutdown();
229
}
230
231
interface StatusListener extends StreamListener {
232
void onStatus(Status status);
233
void onDeletionNotice(StatusDeletionNotice statusDeletionNotice);
234
void onTrackLimitationNotice(int numberOfLimitedStatuses);
235
void onScrubGeo(long userId, long upToStatusId);
236
void onStallWarning(StallWarning warning);
237
}
238
```
239
240
[Real-time Streaming](./streaming.md)
241
242
### Geographic and Places
243
244
Location-based functionality including places, geocoding, and geographic search.
245
246
```java { .api }
247
interface PlacesGeoResources {
248
ResponseList<Place> searchPlaces(GeoQuery query) throws TwitterException;
249
ResponseList<Place> getSimilarPlaces(GeoLocation location, String name, String containedWithin, String streetAddress) throws TwitterException;
250
ResponseList<Place> reverseGeoCode(GeoQuery query) throws TwitterException;
251
Place getGeoDetails(String placeId) throws TwitterException;
252
}
253
```
254
255
[Geographic and Places](./places.md)
256
257
## Core Types
258
259
```java { .api }
260
class TwitterException extends Exception {
261
int getErrorCode();
262
String getErrorMessage();
263
int getStatusCode();
264
boolean isCausedByNetworkIssue();
265
boolean isErrorMessageAvailable();
266
boolean exceededRateLimitation();
267
RateLimitStatus getRateLimitStatus();
268
}
269
270
interface TwitterResponse {
271
RateLimitStatus getRateLimitStatus();
272
int getAccessLevel();
273
}
274
275
interface RateLimitStatus {
276
int getLimit();
277
int getRemaining();
278
int getResetTimeInSeconds();
279
int getSecondsUntilReset();
280
}
281
282
class AccessToken {
283
AccessToken(String token, String tokenSecret);
284
String getToken();
285
String getTokenSecret();
286
long getUserId();
287
String getScreenName();
288
}
289
290
class OAuth2Token {
291
OAuth2Token(String tokenType, String accessToken);
292
String getTokenType();
293
String getAccessToken();
294
}
295
```