Brand new on these forums, brand new to the Twitter API, pretty new to doing serious coding like this. I’m currently just doing some experimenting with trying to upload images with Java code, and I ran into a problem. I keep getting this “Bad Request” error code that I can find nothing about on the documentation, and I have no idea where the issue could come from. I spent 2 hours trying to debug it.
The code uses Google’s java http client, oauth client, and gson JSON methods. These work fine in another endpoint (albeit a V2 endpoint, to be specific the posting a new tweet one). It’s only when I add in the image does it seem to go wrong. I’m not too sure if it has to do with an error in how I am creating the content (the Base64 encoded image, Java related), or something wrong with how I am sending the request (API related). Please do tell me if I should put this question somewhere else. If I print out the String that the image is encoded into, it looks ok (not empty or anything)
Here is the code. Quite a lot of it is pieced together from searches trying to figure out how to do each individual piece.

BufferedImage image = ImageIO.read(new File("cover.jpg"));
ByteArrayOutputStream stream = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", stream);
Map<String, Object> json = new HashMap<String, Object>();
json.put("media_data", Base64.getEncoder().encodeToString(stream.toByteArray()));
System.out.println(Base64.getEncoder().encodeToString(stream.toByteArray()));
HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory();
HttpContent content = new JsonHttpContent(new GsonFactory(), json).setMediaType(new HttpMediaType("multipart/form-data")); 
HttpRequest request = requestFactory.buildPostRequest(new GenericUrl("https://upload.twitter.com/1.1/media/upload.json"), content);
//note: generateOAuth makes and returns a OAuthParameters object which is then used in the request. This code is not the issue, it works with other endpoints.
generateOAuth("POST", new GenericUrl("https://upload.twitter.com/1.1/media/upload.json")).initialize(request);
String response = request.execute().parseAsString();
System.out.println(response);

The response is this: {"errors":[{"code":214,"message":"Bad request."}]}

You’ll have a much easier time using one of the existing libraries to do this, rather than trying to do all the manual code yourself (e.g. https://twitter4j.org/en/index.html).

Then uploading an image looks something like this (I wrote this as a main method, but in reality you’d put some of this stuff in other places - e.g. TwitterFactory can be a private static final variable).


    public static void main(String[] args) {
        // The tweet text you want to use
        String tweetText = "your tweet text";
        // The paths of the images you want to upload
        ArrayList<Path> filePaths = new ArrayList<>();
        TwitterFactory factory = new TwitterFactory(
                new ConfigurationBuilder()
                        .setDebugEnabled(true)
                        .setOAuthConsumerKey("<your API key>")
                        .setOAuthConsumerSecret("<your API secret key>")
                        .setOAuthAccessToken("<your user access token>")
                        .setOAuthAccessTokenSecret("<access token secret>")
                        .setTweetModeExtended(true)
                        .build());
        Twitter twitter = factory.getInstance();
        ArrayList<UploadedMedia> medias = new ArrayList<>();
        try {
            for (int i = 0; i < filePaths.size(); i++) {
                medias.add(twitter.uploadMedia(filePaths.get(i).toFile()));
            }
        } catch (Exception e) {
            System.err.println("Failed to upload media!");
            return;
        }

        StatusUpdate update;
        try {
            update = new StatusUpdate(tweetText);
            long[] mediaIDs = new long[medias.size()];
            for (int i = 0; i < medias.size(); i++) {
                mediaIDs[i] = medias.get(i).getMediaId();
            }
            update.setMediaIds(mediaIDs);
            Status status = twitter.updateStatus(update);
            System.out.println("Status update successful! ID = " + status.getId() + " & text = " + status.getText());
        } catch (TwitterException te) {
            System.out.println("Twitter error: " + te.getErrorMessage());
        } catch (Exception e) {
            System.err.println("Failed to upload to Twitter: " + e.getMessage());
        }
    }

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.