0

I want to post the request in same formate.

    POST /mga/sps/oauth/oauth20/token HTTP/1.1
    Host: example.com
    Content-Type: application/x-www-form-urlencoded
    Authorization: Basic aaabbbCCCdddeeefffGGG
    client_id=xxx&client_secret=yyy&grant_type=authorization_code
    &code=3v6MJzt9vKtRkxpTFnkJG3IyspWC2k
    &redirect_uri=xyz%2Ffolder

I have Implemented but getting bad request and unable to print the post content what I am sending I also want to get the json response after sending this request.

String urlParameters  = "grant_type=authorization_code"+"&redirect_uri="+session.getAttribute("redirect_uri")+"&code_verifier="+session.getAttribute("codeVerifier")+"&code="+session.getAttribute("code")+"&state="+session.getAttribute("state");
        byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
        int postDataLength = postData.length;
        URL url = new URL( "https://example/oauth20/token" );
        HttpURLConnection conn= (HttpURLConnection) url.openConnection();           
        conn.setDoOutput(true);
        conn.setInstanceFollowRedirects(false);
        conn.setRequestMethod("POST");
     
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
        conn.setRequestProperty("charset", "utf-8");
        conn.setRequestProperty("Content-Length", 
       Integer.toString(postDataLength ));
        conn.setRequestProperty("Host","example.com");
        conn.setRequestProperty("Authorization","clientID=xyz");
        conn.setUseCaches(false);
        DataOutputStream wr = new 
       DataOutputStream(conn.getOutputStream());
        wr.write(postData);
        System.out.println(conn.getResponseCode());
        System.out.println(conn.getResponseMessage());
        conn.disconnect();

 
rupesh raj
  • 17
  • 5

1 Answers1

0

You have multiple options.

  1. You can start with Java HTTP Client - Refer

The HTTP Client was added in Java 11. It can be used to request HTTP resources over the network. It supports HTTP/1.1 and HTTP/2, both synchronous and asynchronous programming models, handles request and response bodies as reactive-streams, and follows the familiar builder pattern.

  1. Apache HttpClient - Refer

  2. RestTemplate - Refer

  3. JAX-RS Client - Example

  4. Spring 5 WebClient - Example

  5. OkHttpClient - Example

Comparison

Sibin Rasiya
  • 1,132
  • 1
  • 11
  • 15
  • I implemented one but Getting error bad request and also unable to print the the posted request.. will you check once – rupesh raj May 23 '22 at 12:41