Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 778
Jeremy Rowler Avatar asked Apr 03 '17 07:04

Jeremy Rowler


2 Answers

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.

like image 141
BlackHatSamurai Avatar answered Nov 12 '22 18:11

BlackHatSamurai


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/

like image 38
noahd Avatar answered Nov 12 '22 19:11

noahd