堆栈交换 api post 方法

stack exchange api post method

我正在尝试 upvote 使用 android 中的 stackexchange API 提问。使用 URL https://api.stackexchange.com/2.2/questions/{questionID}/upvote

但在日志中它只是显示这样的东西 org.apache.http.message.BasicHttpResponse@33b2c539

API link 赞一个问题是 https://api.stackexchange.com/docs/upvote-question

当我从 API link 开始尝试时,它可以工作,但不能使用代码。

找到下面的代码:

String url= "https://api.stackexchange.com/2.2/questions/"+questionId+"/upvote";

                HttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url.toString()); 

                List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);

                nameValuePair.add(new BasicNameValuePair("key", key));
                nameValuePair.add(new BasicNameValuePair("access_token", accessToken));

                try {
                        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
                } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                }
                // making request

                try {
                       response = httpClient.execute(httpPost);
                        Log.d("Http Post Response:", response.toString());
                } catch (ClientProtocolException e) {
                        e.printStackTrace();
                } catch (IOException e) {
                        e.printStackTrace();
                }

org.apache.http.message.BasicHttpResponse@33b2c539是因为这一行

       Log.d("Http Post Response:", response.toString());

试试这个

       String result = EntityUtils.toString(response.getEntity());
       Log.d("Http Post Response:", result);

找到解决方案了。 我们应该将 5 个参数传递给 upvote 个问题。

List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(5);
nameValuePair.add(new BasicNameValuePair("key", key));
nameValuePair.add(new BasicNameValuePair("access_token", accessToken));
nameValuePair.add(new BasicNameValuePair("filter", "default"));
nameValuePair.add(new BasicNameValuePair("site", "Whosebug"));
nameValuePair.add(new BasicNameValuePair("preview", "false"));

此外,http 响应是 JSON 格式(预期),但它是 Gzip 类型。 我们需要通过将数据发送到 GZIPInputStream 并以 UTF-8 解码以读取它来解码响应。 (在 api 文档中未提及)

            GZIPInputStream gin = new GZIPInputStream(entity.getContent());
            InputStreamReader ss = new InputStreamReader(gin, "UTF-8");
            BufferedReader br = new BufferedReader(ss);
            String line = "", data="";
            while((line=br.readLine())!=null){
                data+=line;
            }