Not able to do a post request to an authenticated

2019-08-23 17:04发布

问题:

I am not able to do a POST request to the Composer rest server that is authenticated.

  • I have been trying out Hyperledger composer rest server with authentication and multiuser enabled.
  • I have enabled Github based authentication by exporting COMPOSER_PROVIDERS variable and multiuser mode with Wallet and identities .
  • I authenticate the rest server in github and i am able to do rest operations in the Composer Swagger explorer .
  • I am also able to do the rest operations in Postman by passing the url with the access_token . http://localhost:4200/api/Trader?access_token=xxxxxxxxxxx .This works in Postman as well.

Problem is i am not able to do a post request to the composer-rest URL from java code even after passing the access token as param. I have tried with OKHttpClient,Apache HTTPClient, java.net client , CloseableHTTPClient .

All it gives me is

Server returned HTTP response code: 401

In all methods i get an "AUTHORIZATION FAILURE" error .

I dont know if i am missing anything , because i am able to do a rest operation from Postman . I take the code format from Postman itself and paste it in the Java code and it still doesnt work . I dont know what i am doing wrong ,

Suggestions , code snippets ?

THANKS !

回答1:

since you managed to get this running from Postman then you're obviously missing something in your java code.

You probably have the URL correct, but might be missing a header, or a json type or something of the sorts.

Inspect your Postman request and replicate it exactly in your java code, everything, not just the URL.

Keep a log of your request and compare it against the Postman one, to see exactly what the difference is.



回答2:

Try this code to retrieve cookies:

public void getCookieUsingCookieHandler() { 
try {       
    // Instantiate CookieManager;
    // make sure to set CookiePolicy
    CookieManager manager = new CookieManager();
    manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    CookieHandler.setDefault(manager);

    // get content from URLConnection;
    // cookies are set by web site
    URL url = new URL("http://host.example.com");
    URLConnection connection = url.openConnection();
    connection.getContent();

    // get cookies from underlying
    // CookieStore
    CookieStore cookieJar =  manager.getCookieStore();
    List <HttpCookie> cookies =
        cookieJar.getCookies();
    for (HttpCookie cookie : cookies) {
            if (cookie.getName().equalsIgnoreCase("access_token")) {
                System.out.println("CookieHandler retrieved cookie: " + cookie.getValue());
                break;
            }

        }
} catch(Exception e) {
    System.out.println("Unable to get cookie using CookieHandler");
    e.printStackTrace();
}

}

You can refer it from here: https://docs.oracle.com/javase/tutorial/deployment/doingMoreWithRIA/accessingCookies.html