Wordpress oauth2令牌在从浏览器中检查时有效,但如果从Android应用程序调用,则响应为" Oauth2令牌无效"

时间:2017-01-12 19:16:07

标签: android wordpress oauth-2.0

我正在尝试使用Android应用在我的Wordpress博客上发帖。 我得到了回应 {"Content":"{\"error\":\"invalid_token\",\"message\":\"The OAuth2 token is invalid.\"}","Message":"Bad Request","Length":-1,"Type":"application\/json"}

但是当我在浏览器中使用相同的令牌来获取gettin令牌信息时,响应是

{"client_id":"51388","user_id":"114830097","blog_id":"121719179","scope":""}

表示令牌对使用有效。所以我觉得我的代码可能有些问题。

private class PostMakerTask extends AsyncTask<Void,Void,String> {

    @Override
    protected String doInBackground(Void... voids) {
        try {
            String address = "https://public-api.wordpress.com/rest/v1.1/sites/mrzhevskiy.wordpress.com/posts/new";
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("title", mNote.getTitle());
            jsonObject.put("content", mNote.getBody());
            String requestBody = jsonObject.toString();
            URL url = new URL(address);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Authorization","BEARER " + mToken);
            OutputStream outputStream = new BufferedOutputStream(connection.getOutputStream());
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream,"utf-8"));
            writer.write(requestBody);
            writer.flush();
            writer.close();
            outputStream.close();

            InputStream inputStream;
            if(connection.getResponseCode()<HttpURLConnection.HTTP_BAD_REQUEST){
                inputStream = connection.getInputStream();
            } else{
                inputStream = connection.getErrorStream();
            }
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String temp,response = "";
            while ((temp = bufferedReader.readLine()) != null) {
                response += temp;
            }
            JSONObject json = new JSONObject();
            json.put("Content", response);
            json.put("Message", connection.getResponseMessage());
            json.put("Length", connection.getContentLength());
            json.put("Type", connection.getContentType());
            return json.toString();

        }
        catch (IOException | JSONException e){
            return e.toString();
        }
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        Log.i("RESULT: ",s);
    }
}

0 个答案:

没有答案