开发者

401 Unauthorized while using Pinboard API for add post in Android

Hey all, I am using the Pinboard API for adding a post from my Android App. Each time I send the GET request with the required credentials and arguments, I get the 401 Unauthorized response code. I tried the same URL from a PHP code and the post gets added to Pinboard without any errors. Any idea where I am going wrong?

Here's the code:

    private void postToPinboard(){

    String url = "https://.muUsername:myPassword@api.pinboard.in/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开发者_如何学Go-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();
}


I finally got the problem: using Pinboard API requires Android to support HTTP basic authentication. So here's how I got it to work:

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

}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜