如何使用okhttp预编写Reddit帖子

时间:2017-04-03 07:54:57

标签: java android post request reddit

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

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

}

我对使用API​​非常新,我不确定我在寻找什么。以下是用于保存的reddit API的链接

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

提前感谢您的帮助!!!

2 个答案:

答案 0 :(得分:4)

根据文档,看起来您正在格式化POST主体错误。你需要让你的身体看起来像:

<div id="login"  class="container-fluid" style="background-repeat: repeat; background-image: url('body-bg.jpg'); display:flex;">

        <div class="row">
            <div class="col-md-4">
                <img class="myimg" alt="Bootstrap Image Preview" src="logo.png" style="width: 130px;" />
            </div>
            <div class="col-md-4">
                <h3> Welcome to the Award Tracker login page. </h3>
            </div>
            <div class="col-md-4">
                <img class="myimg" alt="Bootstrap Image Preview" src="1stER_icon_256.png" style="width: 130px;" />
            </div>
        </div> <!-- /row -->

        <div class="row">
            <div class="col-md-12">
                <form class="form-signin">
                    <h2 class="form-signin-heading">Please sign in</h2>
                    <input id="accountName" type="text" class="input-block-level" placeholder="Email address">
                    <input id="enterPassword" type="password" class="input-block-level" placeholder="Password">
                    <button id="submit" class="btn btn-large btn-primary" type="submit">Sign in</button>
                </form>
            </div>
        </div> <!-- /row -->

    </div> <!-- /container -->

您似乎错过了{ "category" : "your category" //This could something like "science" "id" : "fullname of thing" } 标题。

Fullname docs

modhash docs

您还需要添加X-Modhash标头。文档解释了这一点。

答案 1 :(得分:2)

您是否尝试过查看okhttp wiki?

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

看起来你走在正确的轨道上,但你可能需要调用execute来获得响应。

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

另外请确保不要在主线程上执行此操作。

我个人喜欢使用改造而不是直接使用okhttp。

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