大家好,
我正在使用Pinboard API从我的Android应用添加帖子。每次我发送带有所需凭据和参数的GET请求时,都会得到401未经授权的响应代码。我从PHP代码尝试了相同的URL,并且帖子被添加到Pinboard中,没有任何错误。
知道我要去哪里错了吗?
这是代码:

    private void postToPinboard(){

    String url = "https://.muUsername:[email protected]/v1/posts/add?";
    HttpClient client = new DefaultHttpClient();
    HttpGet get = new HttpGet(url);

     try {
            // Adding my data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("description","Description data");
            nameValuePairs.add(new BasicNameValuePair("url", "http://somewebsite.com"));

            String paramString = URLEncodedUtils.format(nameValuePairs, "utf-8");
            url +=paramString;

            // Execute HTTP Post Request
            HttpResponse response = client.execute(get);

            Log.v("", "RESPONSE CODE: "+response.getStatusLine());// giving 401 Unauthorized

        } catch (ClientProtocolException e) {
            // do something
        } catch (IOException e) {
            // do domething
        }
        finish();
}

最佳答案

我终于明白了问题:使用Pinboard API要求Android支持HTTP基本身份验证。所以这是我如何使其工作:

    private void postToPinboard(){

        String url ="https://api.pinboard.in/v1/posts/add?";

        DefaultHttpClient client = new DefaultHttpClient();

    String credentials = Base64.encodeBytes((username+":"+password).getBytes());

    if(credentials!=null){

        try {

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

            nameValuePairs.add(new BasicNameValuePair("description", "Description data");
            nameValuePairs.add(new BasicNameValuePair("url", "http://somewebsite.com"));

            String paramString = URLEncodedUtils.format(nameValuePairs, "utf-8");

            url +=paramString;

            HttpGet get = new HttpGet(url);
            get.addHeader("Authorization","Basic "+credentials);

           HttpResponse response = client.execute(get);

               if(response.getStatusLine().getStatusCode() == 200){
                   //       Added to pinboard
               }else{
                   //       Error adding to Pinboard
               }

        } catch (ClientProtocolException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
finish();


}

10-08 06:22