Jeremy Rowler
Jeremy Rowler

Reputation: 387

How to preform a Reddit post with okhttp

I am trying to use the Reddit API to save a post. I know I am formatting the request wrong, but I can't seem to find any documentation on how to do it correctly. If anyone could either lead me in the right direction, or help me format the request correctly. This is what I have so far.

    public void save(View v)
{
    OkHttpClient client = new OkHttpClient();
    String authString = MainActivity.CLIENT_ID + ":";
    String encodedAuthString = Base64.encodeToString(authString.getBytes(),
            Base64.NO_WRAP);
    System.out.println("myaccesstoken is: "+ myaccesstoken);
    System.out.println("the image id is: "+ myimageid);
    Request request = new Request.Builder()
            .addHeader("User-Agent", "Sample App")
            .addHeader("Authorization", "Bearer " + myaccesstoken)
            .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
            .url("https://oauth.reddit.com/api/save.json?")
            .post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"),
                    ""+ myimageid +
                            "1"))
            .build();

    client.newCall(request);

}

I am very very new to using APIs and I am not sure exactly what I am looking for. Here is the link to the reddit API for saving

https://www.reddit.com/dev/api/oauth#POST_api_save

Thank you in advance for any help!!!

Upvotes: 6

Views: 372

Answers (2)

BlackHatSamurai
BlackHatSamurai

Reputation: 23503

According to the documentation, it looks like you are formatting to POST body incorrectly. You need to make your body look like:

{
"category" : "your category" //This could something like "science"
"id" : "fullname of thing" 
}

It also looks like you are missing the X-Modhash header.

Fullname docs

modhash docs

You will also need to include a X-Modhash header. The documentation explains that here.

Upvotes: 4

noahd
noahd

Reputation: 862

Did you try looking at the okhttp wiki?

https://github.com/square/okhttp/wiki/Recipes

It looks like you are on the right track but you probably need to call execute to get the response.

Response response = client.newCall(request).execute();

Also make sure not to do this on the main thread.

I personally like to use retrofit instead of using okhttp directly.

https://square.github.io/retrofit/

Upvotes: 2

Related Questions