堆栈交换api post方法

时间:2015-04-25 20:12:04

标签: android http-post stackexchange-api

我正在尝试使用android中的stackexchange api来提出问题。使用网址 https://api.stackexchange.com/2.2/questions/ {questionID} /给予好评

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

用于upvote问题的API链接是 https://api.stackexchange.com/docs/upvote-question

当我尝试从api链接工作时,但不是代码。

在下面找到以下代码:

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

2 个答案:

答案 0 :(得分:3)

得到了解决方案。 我们应该通过5个参数来提出问题。

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", "stackoverflow"));
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;
            }

答案 1 :(得分:0)

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