How to preform a Reddit post with okhttp
Asked Answered
S

2

6

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!!!

Semipalatinsk answered 3/4, 2017 at 7:54 Comment(2)
can you provide the logcat?Spandau
Are you trying to save the whole post or just the link or the comment?Napoli
N
4

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.

Napoli answered 15/4, 2017 at 2:57 Comment(0)
O
2

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/

Ostracize answered 14/4, 2017 at 20:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.