如何使用 okhttp 执行 Reddit post

How to preform a Reddit post with okhttp

我正在尝试使用 Reddit API 来保存 post。我知道我的请求格式有误,但我似乎找不到任何有关如何正确执行此操作的文档。如果有人能引导我朝着正确的方向前进,或者帮助我正确地格式化请求。这是我目前所拥有的。

    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);

}

我对使用 APIs 非常陌生,我不确定我在寻找什么。这是 link 到 reddit API 的保存

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

提前感谢您的帮助!!!

您是否尝试查看 okhttp wiki?

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

看来您的方向是正确的,但您可能需要调用执行程序才能获得响应。

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

还要确保不要在主线程上执行此操作。

我个人喜欢用retrofit而不是直接用okhttp

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

根据文档,您似乎错误地格式化为 POST body。您需要使 body 看起来像:

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

您似乎还缺少 X-Modhash header。

Fullname docs

modhash docs

您还需要包含 X-Modhash header。文档在此处对此进行了解释。