Response and response body for other than 201 status codes not found












0















I'm trying to fetch the error response from the graph api while creating the user on AD but not able to capture the response from the api for other than 201 which is a user created successfully.



HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(new MediaType { MediaType.APPLICATION_JSON }));
headers.set("Authorization", "Bearer " + token);
headers.set("Content-Type", "application/json");
try{
HttpEntity<String> request = new HttpEntity<String>(jsonRequest.toString(), headers);
responseEntity = restTemplate.postForEntity(graphUrl, request, String.class);
}catch(Exception e){
System.out.println("Result - status ("+ responseEntity.getStatusCode() + ") has body: " + responseEntity.hasBody());
}


Whenever the response is other than 201 it show me an exception Bad Request 400



I'm getting a error response with postman but with same payload the response is null in Java app










share|improve this question

























  • To get the error response in code, you could refer to here.

    – SunnySun
    Jan 2 at 5:38











  • My response itself is null. The quoted example has more about processing the response.

    – prabas
    Jan 2 at 20:30
















0















I'm trying to fetch the error response from the graph api while creating the user on AD but not able to capture the response from the api for other than 201 which is a user created successfully.



HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(new MediaType { MediaType.APPLICATION_JSON }));
headers.set("Authorization", "Bearer " + token);
headers.set("Content-Type", "application/json");
try{
HttpEntity<String> request = new HttpEntity<String>(jsonRequest.toString(), headers);
responseEntity = restTemplate.postForEntity(graphUrl, request, String.class);
}catch(Exception e){
System.out.println("Result - status ("+ responseEntity.getStatusCode() + ") has body: " + responseEntity.hasBody());
}


Whenever the response is other than 201 it show me an exception Bad Request 400



I'm getting a error response with postman but with same payload the response is null in Java app










share|improve this question

























  • To get the error response in code, you could refer to here.

    – SunnySun
    Jan 2 at 5:38











  • My response itself is null. The quoted example has more about processing the response.

    – prabas
    Jan 2 at 20:30














0












0








0








I'm trying to fetch the error response from the graph api while creating the user on AD but not able to capture the response from the api for other than 201 which is a user created successfully.



HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(new MediaType { MediaType.APPLICATION_JSON }));
headers.set("Authorization", "Bearer " + token);
headers.set("Content-Type", "application/json");
try{
HttpEntity<String> request = new HttpEntity<String>(jsonRequest.toString(), headers);
responseEntity = restTemplate.postForEntity(graphUrl, request, String.class);
}catch(Exception e){
System.out.println("Result - status ("+ responseEntity.getStatusCode() + ") has body: " + responseEntity.hasBody());
}


Whenever the response is other than 201 it show me an exception Bad Request 400



I'm getting a error response with postman but with same payload the response is null in Java app










share|improve this question
















I'm trying to fetch the error response from the graph api while creating the user on AD but not able to capture the response from the api for other than 201 which is a user created successfully.



HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(new MediaType { MediaType.APPLICATION_JSON }));
headers.set("Authorization", "Bearer " + token);
headers.set("Content-Type", "application/json");
try{
HttpEntity<String> request = new HttpEntity<String>(jsonRequest.toString(), headers);
responseEntity = restTemplate.postForEntity(graphUrl, request, String.class);
}catch(Exception e){
System.out.println("Result - status ("+ responseEntity.getStatusCode() + ") has body: " + responseEntity.hasBody());
}


Whenever the response is other than 201 it show me an exception Bad Request 400



I'm getting a error response with postman but with same payload the response is null in Java app







azure-ad-graph-api






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 2 at 20:32







prabas

















asked Jan 1 at 10:14









prabasprabas

1816




1816













  • To get the error response in code, you could refer to here.

    – SunnySun
    Jan 2 at 5:38











  • My response itself is null. The quoted example has more about processing the response.

    – prabas
    Jan 2 at 20:30



















  • To get the error response in code, you could refer to here.

    – SunnySun
    Jan 2 at 5:38











  • My response itself is null. The quoted example has more about processing the response.

    – prabas
    Jan 2 at 20:30

















To get the error response in code, you could refer to here.

– SunnySun
Jan 2 at 5:38





To get the error response in code, you could refer to here.

– SunnySun
Jan 2 at 5:38













My response itself is null. The quoted example has more about processing the response.

– prabas
Jan 2 at 20:30





My response itself is null. The quoted example has more about processing the response.

– prabas
Jan 2 at 20:30












2 Answers
2






active

oldest

votes


















1














Spring's RestTemplate and Spring Boot's TestRestTemplate will on JDK's internal HttpURLConnection implementation by default, which fails to access the body of an HTTP-response with status 401 "Unauthorized". You could use HTTPClient which doesn't face the problem.
enter image description here



You could refer to the following workgroup:






<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version> <scope>test</scope>
</dependency>

String token="eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Im5iQ3dXMTF3M1hrQi14VWFYd0tSU0xqTUhHUSIsImtpZCI6Im5iQ3dXMTF3M1hrQi14VWFYd0tSU0xqTUhHUSJ9.eyJhdWQiOiJodHRwczovL21hbmFnZW1lbnQuYXp1cmUuY29tLyIsImlzcyI6Imh0dHBzOi8vc3RzLndpbmRvd3MubmV0L2U0YzlhYjRlLWJkMjctNDBkNS04NDU5LTIzMGJhMmE3NTdmYi8iLCJpYXQiOjE1NDY1NzkxNTgsIm5iZiI6MTU0NjU3OTE1OCwiZXhwIjoxNTQ2NTgzMDU4LCJhaW8iOiI0MlJnWU5qSG45NTBZV0p5dXIvZXozL0trNm9iQUE9PSIsImFwcGlkIjoiNjNkMzk0ZDctYjA1OC00MDRkLWJjYjMtMThmODhmN2UzY2FhIiwiYXBwaWRhY3IiOiIxIiwiaWRwIjoiaHR0cHM6Ly9zdHMud2luZG93cy5uZXQvZTRjOWFiNGUtYmQyNy00MGQ1LTg0NTktMjMwYmEyYTc1N2ZiLyIsIm9pZCI6ImZiZmVkNzhiLWNkYWUtNDU3NC05YzM4LTY0MjlmMjI2MTMyOCIsInN1YiI6ImZiZmVkNzhiLWNkYWUtNDU3NC05YzM4LTY0MjlmMjI2MTMyOCIsInRpZCI6ImU0YzlhYjRlLWJkMjctNDBkNS04NDU5LTIzMGJhMmE3NTdmYiIsInV0aSI6IlVTRzMzM3B3Q2tDc3MxN3ZRdVFDQUEiLCJ2ZXIiOiIxLjAifQ.cFfptQOBt_BQKAbOSFsewmAMsgku15G8oKrfTuxD8ID2AZYtIWqEt1kFXKYBb66Hmsephe_KgyyeByIY_RLPW7JT3cpMTiSkh1DsiRvdAJJkZ0fcmgWQsZB-mmsS-Kt5vTUO1F5EtNeneaaklexfuEMG9E_hUiPKM2v46LlD3pO9ZPlq45157nUMcxPJlPpeHoE3riXwBEUQTCUFTm60NHOG1Cs_NuC_bVHBC3oN-pCFabz-vMo4O2Zikxn6S-BYxz909EP5lAmRNjKgH3uPYHS5rWfve20NiUPy8nOyBHKgz6XxAJXz7PVxm_hTOtdsGC9Hg8bdxnOKctPo95vAlQ";
String jsonRequest="{"test":"a"}";
String graphUrl="https://graph.microsoft.com/v1.0/users";
HttpClient client = new HttpClient();
PostMethod postMethod = new PostMethod(graphUrl);
postMethod.setRequestHeader("Content-Type", "application/json");
postMethod.setRequestHeader("Authorization", "Bearer " + token);
postMethod.setRequestBody(jsonRequest);
try {
int code = client.executeMethod(postMethod);
String res = postMethod.getResponseBodyAsString();
System.out.print(res);
} catch (IOException e) {
e.printStackTrace();
}





And you could refer to other information here.






share|improve this answer


























  • I have tried the above snipped. getting error Cannot instantiate the type HttpClient PostMethod cannot be resolved to a type Updated the pom.xml but still the app shows error

    – prabas
    Jan 6 at 4:28













  • After some changes i could see the response as above screenshot for 401, but azure graph api has response code 400 where in if the user already exists the api will return an exact error code. I'm not getting that response now.

    – prabas
    Jan 6 at 9:41













  • Cloud you share the error code here? What did it return for the code = client.executeMethod(postMethod) and res = postMethod.getResponseBodyAsString()?

    – SunnySun
    Jan 8 at 7:11











  • The code below worked for me. when I used String res = postMethod.getResponseBodyAsString(); worked fine when there is 401, but failed to capture other response like 400. Thank you for pointing me to HttpClient usage. It solved my issue.

    – prabas
    Jan 9 at 12:28













  • @prabas, you're welcome. If you think it is useful, please make a mark for it, thanks.

    – SunnySun
    Jan 10 at 2:31



















0














StringEntity postStr = new StringEntity(jsonRequest); 
CloseableHttpClient client = HttpClients.createDefault();
HttpPost postM = new HttpPost(graphUrl);
postM.setHeader("Content-Type", "application/json");
postM.setHeader("Authorization", "Bearer " +token);
postM.setEntity(postStr);
try {
CloseableHttpResponse response = client.execute(postMethod);
int statusCode = response.getStatusLine().getStatusCode();

if(statusCode == 201){
String res = EntityUtils.toString(response.getEntity());
}


The code above worked for me.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53994638%2fresponse-and-response-body-for-other-than-201-status-codes-not-found%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    Spring's RestTemplate and Spring Boot's TestRestTemplate will on JDK's internal HttpURLConnection implementation by default, which fails to access the body of an HTTP-response with status 401 "Unauthorized". You could use HTTPClient which doesn't face the problem.
    enter image description here



    You could refer to the following workgroup:






    <dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.6</version> <scope>test</scope>
    </dependency>

    String token="eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Im5iQ3dXMTF3M1hrQi14VWFYd0tSU0xqTUhHUSIsImtpZCI6Im5iQ3dXMTF3M1hrQi14VWFYd0tSU0xqTUhHUSJ9.eyJhdWQiOiJodHRwczovL21hbmFnZW1lbnQuYXp1cmUuY29tLyIsImlzcyI6Imh0dHBzOi8vc3RzLndpbmRvd3MubmV0L2U0YzlhYjRlLWJkMjctNDBkNS04NDU5LTIzMGJhMmE3NTdmYi8iLCJpYXQiOjE1NDY1NzkxNTgsIm5iZiI6MTU0NjU3OTE1OCwiZXhwIjoxNTQ2NTgzMDU4LCJhaW8iOiI0MlJnWU5qSG45NTBZV0p5dXIvZXozL0trNm9iQUE9PSIsImFwcGlkIjoiNjNkMzk0ZDctYjA1OC00MDRkLWJjYjMtMThmODhmN2UzY2FhIiwiYXBwaWRhY3IiOiIxIiwiaWRwIjoiaHR0cHM6Ly9zdHMud2luZG93cy5uZXQvZTRjOWFiNGUtYmQyNy00MGQ1LTg0NTktMjMwYmEyYTc1N2ZiLyIsIm9pZCI6ImZiZmVkNzhiLWNkYWUtNDU3NC05YzM4LTY0MjlmMjI2MTMyOCIsInN1YiI6ImZiZmVkNzhiLWNkYWUtNDU3NC05YzM4LTY0MjlmMjI2MTMyOCIsInRpZCI6ImU0YzlhYjRlLWJkMjctNDBkNS04NDU5LTIzMGJhMmE3NTdmYiIsInV0aSI6IlVTRzMzM3B3Q2tDc3MxN3ZRdVFDQUEiLCJ2ZXIiOiIxLjAifQ.cFfptQOBt_BQKAbOSFsewmAMsgku15G8oKrfTuxD8ID2AZYtIWqEt1kFXKYBb66Hmsephe_KgyyeByIY_RLPW7JT3cpMTiSkh1DsiRvdAJJkZ0fcmgWQsZB-mmsS-Kt5vTUO1F5EtNeneaaklexfuEMG9E_hUiPKM2v46LlD3pO9ZPlq45157nUMcxPJlPpeHoE3riXwBEUQTCUFTm60NHOG1Cs_NuC_bVHBC3oN-pCFabz-vMo4O2Zikxn6S-BYxz909EP5lAmRNjKgH3uPYHS5rWfve20NiUPy8nOyBHKgz6XxAJXz7PVxm_hTOtdsGC9Hg8bdxnOKctPo95vAlQ";
    String jsonRequest="{"test":"a"}";
    String graphUrl="https://graph.microsoft.com/v1.0/users";
    HttpClient client = new HttpClient();
    PostMethod postMethod = new PostMethod(graphUrl);
    postMethod.setRequestHeader("Content-Type", "application/json");
    postMethod.setRequestHeader("Authorization", "Bearer " + token);
    postMethod.setRequestBody(jsonRequest);
    try {
    int code = client.executeMethod(postMethod);
    String res = postMethod.getResponseBodyAsString();
    System.out.print(res);
    } catch (IOException e) {
    e.printStackTrace();
    }





    And you could refer to other information here.






    share|improve this answer


























    • I have tried the above snipped. getting error Cannot instantiate the type HttpClient PostMethod cannot be resolved to a type Updated the pom.xml but still the app shows error

      – prabas
      Jan 6 at 4:28













    • After some changes i could see the response as above screenshot for 401, but azure graph api has response code 400 where in if the user already exists the api will return an exact error code. I'm not getting that response now.

      – prabas
      Jan 6 at 9:41













    • Cloud you share the error code here? What did it return for the code = client.executeMethod(postMethod) and res = postMethod.getResponseBodyAsString()?

      – SunnySun
      Jan 8 at 7:11











    • The code below worked for me. when I used String res = postMethod.getResponseBodyAsString(); worked fine when there is 401, but failed to capture other response like 400. Thank you for pointing me to HttpClient usage. It solved my issue.

      – prabas
      Jan 9 at 12:28













    • @prabas, you're welcome. If you think it is useful, please make a mark for it, thanks.

      – SunnySun
      Jan 10 at 2:31
















    1














    Spring's RestTemplate and Spring Boot's TestRestTemplate will on JDK's internal HttpURLConnection implementation by default, which fails to access the body of an HTTP-response with status 401 "Unauthorized". You could use HTTPClient which doesn't face the problem.
    enter image description here



    You could refer to the following workgroup:






    <dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4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G1Cs_NuC_bVHBC3oN-pCFabz-vMo4O2Zikxn6S-BYxz909EP5lAmRNjKgH3uPYHS5rWfve20NiUPy8nOyBHKgz6XxAJXz7PVxm_hTOtdsGC9Hg8bdxnOKctPo95vAlQ";
    String jsonRequest="{"test":"a"}";
    String graphUrl="https://graph.microsoft.com/v1.0/users";
    HttpClient client = new HttpClient();
    PostMethod postMethod = new PostMethod(graphUrl);
    postMethod.setRequestHeader("Content-Type", "application/json");
    postMethod.setRequestHeader("Authorization", "Bearer " + token);
    postMethod.setRequestBody(jsonRequest);
    try {
    int code = client.executeMethod(postMethod);
    String res = postMethod.getResponseBodyAsString();
    System.out.print(res);
    } catch (IOException e) {
    e.printStackTrace();
    }





    And you could refer to other information here.






    share|improve this answer


























    • I have tried the above snipped. getting error Cannot instantiate the type HttpClient PostMethod cannot be resolved to a type Updated the pom.xml but still the app shows error

      – prabas
      Jan 6 at 4:28













    • After some changes i could see the response as above screenshot for 401, but azure graph api has response code 400 where in if the user already exists the api will return an exact error code. I'm not getting that response now.

      – prabas
      Jan 6 at 9:41













    • Cloud you share the error code here? What did it return for the code = client.executeMethod(postMethod) and res = postMethod.getResponseBodyAsString()?

      – SunnySun
      Jan 8 at 7:11











    • The code below worked for me. when I used String res = postMethod.getResponseBodyAsString(); worked fine when there is 401, but failed to capture other response like 400. Thank you for pointing me to HttpClient usage. It solved my issue.

      – prabas
      Jan 9 at 12:28













    • @prabas, you're welcome. If you think it is useful, please make a mark for it, thanks.

      – SunnySun
      Jan 10 at 2:31














    1












    1








    1







    Spring's RestTemplate and Spring Boot's TestRestTemplate will on JDK's internal HttpURLConnection implementation by default, which fails to access the body of an HTTP-response with status 401 "Unauthorized". You could use HTTPClient which doesn't face the problem.
    enter image description here



    You could refer to the following workgroup:






    <dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.6</version> <scope>test</scope>
    </dependency>

    String token="eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1N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S5rWfve20NiUPy8nOyBHKgz6XxAJXz7PVxm_hTOtdsGC9Hg8bdxnOKctPo95vAlQ";
    String jsonRequest="{"test":"a"}";
    String graphUrl="https://graph.microsoft.com/v1.0/users";
    HttpClient client = new HttpClient();
    PostMethod postMethod = new PostMethod(graphUrl);
    postMethod.setRequestHeader("Content-Type", "application/json");
    postMethod.setRequestHeader("Authorization", "Bearer " + token);
    postMethod.setRequestBody(jsonRequest);
    try {
    int code = client.executeMethod(postMethod);
    String res = postMethod.getResponseBodyAsString();
    System.out.print(res);
    } catch (IOException e) {
    e.printStackTrace();
    }





    And you could refer to other information here.






    share|improve this answer















    Spring's RestTemplate and Spring Boot's TestRestTemplate will on JDK's internal HttpURLConnection implementation by default, which fails to access the body of an HTTP-response with status 401 "Unauthorized". You could use HTTPClient which doesn't face the problem.
    enter image description here



    You could refer to the following workgroup:






    <dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.6</version> <scope>test</scope>
    </dependency>

    String token="eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Im5iQ3dXMTF3M1hrQi14VWFYd0tSU0xqTUhHUSIsImtpZCI6Im5iQ3dXMTF3M1hrQi14VWFYd0tSU0xqTUhHUSJ9.eyJhdWQiOiJodHRwczovL21hbmFnZW1lbnQuYXp1cmUuY29tLyIsImlzcyI6Imh0dHBzOi8vc3RzLndpbmRvd3MubmV0L2U0YzlhYjRlLWJkMjctNDBkNS04NDU5LTIzMGJhMmE3NTdmYi8iLCJpYXQiOjE1NDY1NzkxNTgsIm5iZiI6MTU0NjU3OTE1OCwiZXhwIjoxNTQ2NTgzMDU4LCJhaW8iOiI0MlJnWU5qSG45NTBZV0p5dXIvZXozL0trNm9iQUE9PSIsImFwcGlkIjoiNjNkMzk0ZDctYjA1OC00MDRkLWJjYjMtMThmODhmN2UzY2FhIiwiYXBwaWRhY3IiOiIxIiwiaWRwIjoiaHR0cHM6Ly9zdHMud2luZG93cy5uZXQvZTRjOWFiNGUtYmQyNy00MGQ1LTg0NTktMjMwYmEyYTc1N2ZiLyIsIm9pZCI6ImZiZmVkNzhiLWNkYWUtNDU3NC05YzM4LTY0MjlmMjI2MTMyOCIsInN1YiI6ImZiZmVkNzhiLWNkYWUtNDU3NC05YzM4LTY0MjlmMjI2MTMyOCIsInRpZCI6ImU0YzlhYjRlLWJkMjctNDBkNS04NDU5LTIzMGJhMmE3NTdmYiIsInV0aSI6IlVTRzMzM3B3Q2tDc3MxN3ZRdVFDQUEiLCJ2ZXIiOiIxLjAifQ.cFfptQOBt_BQKAbOSFsewmAMsgku15G8oKrfTuxD8ID2AZYtIWqEt1kFXKYBb66Hmsephe_KgyyeByIY_RLPW7JT3cpMTiSkh1DsiRvdAJJkZ0fcmgWQsZB-mmsS-Kt5vTUO1F5EtNeneaaklexfuEMG9E_hUiPKM2v46LlD3pO9ZPlq45157nUMcxPJlPpeHoE3riXwBEUQTCUFTm60NHOG1Cs_NuC_bVHBC3oN-pCFabz-vMo4O2Zikxn6S-BYxz909EP5lAmRNjKgH3uPYHS5rWfve20NiUPy8nOyBHKgz6XxAJXz7PVxm_hTOtdsGC9Hg8bdxnOKctPo95vAlQ";
    String jsonRequest="{"test":"a"}";
    String graphUrl="https://graph.microsoft.com/v1.0/users";
    HttpClient client = new HttpClient();
    PostMethod postMethod = new PostMethod(graphUrl);
    postMethod.setRequestHeader("Content-Type", "application/json");
    postMethod.setRequestHeader("Authorization", "Bearer " + token);
    postMethod.setRequestBody(jsonRequest);
    try {
    int code = client.executeMethod(postMethod);
    String res = postMethod.getResponseBodyAsString();
    System.out.print(res);
    } catch (IOException e) {
    e.printStackTrace();
    }





    And you could refer to other information here.






    <dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.6</version> <scope>test</scope>
    </dependency>

    String token="eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Im5iQ3dXMTF3M1hrQi14V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xm_hTOtdsGC9Hg8bdxnOKctPo95vAlQ";
    String jsonRequest="{"test":"a"}";
    String graphUrl="https://graph.microsoft.com/v1.0/users";
    HttpClient client = new HttpClient();
    PostMethod postMethod = new PostMethod(graphUrl);
    postMethod.setRequestHeader("Content-Type", "application/json");
    postMethod.setRequestHeader("Authorization", "Bearer " + token);
    postMethod.setRequestBody(jsonRequest);
    try {
    int code = client.executeMethod(postMethod);
    String res = postMethod.getResponseBodyAsString();
    System.out.print(res);
    } catch (IOException e) {
    e.printStackTrace();
    }





    <dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.6</version> <scope>test</scope>
    </dependency>

    String token="eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Im5iQ3dXMTF3M1hrQi14VWFYd0tSU0xqTUhHUSIsImtpZCI6Im5iQ3dXMTF3M1hrQi14VWFYd0tSU0xqTUhHUSJ9.eyJhdWQiOiJodHRwczovL21hbmFnZW1lbnQuYXp1cmUuY29tLyIsImlzcyI6Imh0dHBzOi8vc3RzLndpbmRvd3MubmV0L2U0YzlhYjRlLWJkMjctNDBkNS04NDU5LTIzMGJhMmE3NTdmYi8iLCJpYXQiOjE1NDY1NzkxNTgsIm5iZiI6MTU0NjU3OTE1OCwiZXhwIjoxNTQ2NTgzMDU4LCJhaW8iOiI0MlJnWU5qSG45NTBZV0p5dXIvZXozL0trNm9iQUE9PSIsImFwcGlkIjoiNjNkMzk0ZDctYjA1OC00MDRkLWJjYjMtMThmODhmN2UzY2FhIiwiYXBwaWRhY3IiOiIxIiwiaWRwIjoiaHR0cHM6Ly9zdHMud2luZG93cy5uZXQvZTRjOWFiNGUtYmQyNy00MGQ1LTg0NTktMjMwYmEyYTc1N2ZiLyIsIm9pZCI6ImZiZmVkNzhiLWNkYWUtNDU3NC05YzM4LTY0MjlmMjI2MTMyOCIsInN1YiI6ImZiZmVkNzhiLWNkYWUtNDU3NC05YzM4LTY0MjlmMjI2MTMyOCIsInRpZCI6ImU0YzlhYjRlLWJkMjctNDBkNS04NDU5LTIzMGJhMmE3NTdmYiIsInV0aSI6IlVTRzMzM3B3Q2tDc3MxN3ZRdVFDQUEiLCJ2ZXIiOiIxLjAifQ.cFfptQOBt_BQKAbOSFsewmAMsgku15G8oKrfTuxD8ID2AZYtIWqEt1kFXKYBb66Hmsephe_KgyyeByIY_RLPW7JT3cpMTiSkh1DsiRvdAJJkZ0fcmgWQsZB-mmsS-Kt5vTUO1F5EtNeneaaklexfuEMG9E_hUiPKM2v46LlD3pO9ZPlq45157nUMcxPJlPpeHoE3riXwBEUQTCUFTm60NHOG1Cs_NuC_bVHBC3oN-pCFabz-vMo4O2Zikxn6S-BYxz909EP5lAmRNjKgH3uPYHS5rWfve20NiUPy8nOyBHKgz6XxAJXz7PVxm_hTOtdsGC9Hg8bdxnOKctPo95vAlQ";
    String jsonRequest="{"test":"a"}";
    String graphUrl="https://graph.microsoft.com/v1.0/users";
    HttpClient client = new HttpClient();
    PostMethod postMethod = new PostMethod(graphUrl);
    postMethod.setRequestHeader("Content-Type", "application/json");
    postMethod.setRequestHeader("Authorization", "Bearer " + token);
    postMethod.setRequestBody(jsonRequest);
    try {
    int code = client.executeMethod(postMethod);
    String res = postMethod.getResponseBodyAsString();
    System.out.print(res);
    } catch (IOException e) {
    e.printStackTrace();
    }






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Jan 4 at 6:54

























    answered Jan 4 at 6:46









    SunnySunSunnySun

    1,308118




    1,308118













    • I have tried the above snipped. getting error Cannot instantiate the type HttpClient PostMethod cannot be resolved to a type Updated the pom.xml but still the app shows error

      – prabas
      Jan 6 at 4:28













    • After some changes i could see the response as above screenshot for 401, but azure graph api has response code 400 where in if the user already exists the api will return an exact error code. I'm not getting that response now.

      – prabas
      Jan 6 at 9:41













    • Cloud you share the error code here? What did it return for the code = client.executeMethod(postMethod) and res = postMethod.getResponseBodyAsString()?

      – SunnySun
      Jan 8 at 7:11











    • The code below worked for me. when I used String res = postMethod.getResponseBodyAsString(); worked fine when there is 401, but failed to capture other response like 400. Thank you for pointing me to HttpClient usage. It solved my issue.

      – prabas
      Jan 9 at 12:28













    • @prabas, you're welcome. If you think it is useful, please make a mark for it, thanks.

      – SunnySun
      Jan 10 at 2:31



















    • I have tried the above snipped. getting error Cannot instantiate the type HttpClient PostMethod cannot be resolved to a type Updated the pom.xml but still the app shows error

      – prabas
      Jan 6 at 4:28













    • After some changes i could see the response as above screenshot for 401, but azure graph api has response code 400 where in if the user already exists the api will return an exact error code. I'm not getting that response now.

      – prabas
      Jan 6 at 9:41













    • Cloud you share the error code here? What did it return for the code = client.executeMethod(postMethod) and res = postMethod.getResponseBodyAsString()?

      – SunnySun
      Jan 8 at 7:11











    • The code below worked for me. when I used String res = postMethod.getResponseBodyAsString(); worked fine when there is 401, but failed to capture other response like 400. Thank you for pointing me to HttpClient usage. It solved my issue.

      – prabas
      Jan 9 at 12:28













    • @prabas, you're welcome. If you think it is useful, please make a mark for it, thanks.

      – SunnySun
      Jan 10 at 2:31

















    I have tried the above snipped. getting error Cannot instantiate the type HttpClient PostMethod cannot be resolved to a type Updated the pom.xml but still the app shows error

    – prabas
    Jan 6 at 4:28







    I have tried the above snipped. getting error Cannot instantiate the type HttpClient PostMethod cannot be resolved to a type Updated the pom.xml but still the app shows error

    – prabas
    Jan 6 at 4:28















    After some changes i could see the response as above screenshot for 401, but azure graph api has response code 400 where in if the user already exists the api will return an exact error code. I'm not getting that response now.

    – prabas
    Jan 6 at 9:41







    After some changes i could see the response as above screenshot for 401, but azure graph api has response code 400 where in if the user already exists the api will return an exact error code. I'm not getting that response now.

    – prabas
    Jan 6 at 9:41















    Cloud you share the error code here? What did it return for the code = client.executeMethod(postMethod) and res = postMethod.getResponseBodyAsString()?

    – SunnySun
    Jan 8 at 7:11





    Cloud you share the error code here? What did it return for the code = client.executeMethod(postMethod) and res = postMethod.getResponseBodyAsString()?

    – SunnySun
    Jan 8 at 7:11













    The code below worked for me. when I used String res = postMethod.getResponseBodyAsString(); worked fine when there is 401, but failed to capture other response like 400. Thank you for pointing me to HttpClient usage. It solved my issue.

    – prabas
    Jan 9 at 12:28







    The code below worked for me. when I used String res = postMethod.getResponseBodyAsString(); worked fine when there is 401, but failed to capture other response like 400. Thank you for pointing me to HttpClient usage. It solved my issue.

    – prabas
    Jan 9 at 12:28















    @prabas, you're welcome. If you think it is useful, please make a mark for it, thanks.

    – SunnySun
    Jan 10 at 2:31





    @prabas, you're welcome. If you think it is useful, please make a mark for it, thanks.

    – SunnySun
    Jan 10 at 2:31













    0














    StringEntity postStr = new StringEntity(jsonRequest); 
    CloseableHttpClient client = HttpClients.createDefault();
    HttpPost postM = new HttpPost(graphUrl);
    postM.setHeader("Content-Type", "application/json");
    postM.setHeader("Authorization", "Bearer " +token);
    postM.setEntity(postStr);
    try {
    CloseableHttpResponse response = client.execute(postMethod);
    int statusCode = response.getStatusLine().getStatusCode();

    if(statusCode == 201){
    String res = EntityUtils.toString(response.getEntity());
    }


    The code above worked for me.






    share|improve this answer




























      0














      StringEntity postStr = new StringEntity(jsonRequest); 
      CloseableHttpClient client = HttpClients.createDefault();
      HttpPost postM = new HttpPost(graphUrl);
      postM.setHeader("Content-Type", "application/json");
      postM.setHeader("Authorization", "Bearer " +token);
      postM.setEntity(postStr);
      try {
      CloseableHttpResponse response = client.execute(postMethod);
      int statusCode = response.getStatusLine().getStatusCode();

      if(statusCode == 201){
      String res = EntityUtils.toString(response.getEntity());
      }


      The code above worked for me.






      share|improve this answer


























        0












        0








        0







        StringEntity postStr = new StringEntity(jsonRequest); 
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost postM = new HttpPost(graphUrl);
        postM.setHeader("Content-Type", "application/json");
        postM.setHeader("Authorization", "Bearer " +token);
        postM.setEntity(postStr);
        try {
        CloseableHttpResponse response = client.execute(postMethod);
        int statusCode = response.getStatusLine().getStatusCode();

        if(statusCode == 201){
        String res = EntityUtils.toString(response.getEntity());
        }


        The code above worked for me.






        share|improve this answer













        StringEntity postStr = new StringEntity(jsonRequest); 
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost postM = new HttpPost(graphUrl);
        postM.setHeader("Content-Type", "application/json");
        postM.setHeader("Authorization", "Bearer " +token);
        postM.setEntity(postStr);
        try {
        CloseableHttpResponse response = client.execute(postMethod);
        int statusCode = response.getStatusLine().getStatusCode();

        if(statusCode == 201){
        String res = EntityUtils.toString(response.getEntity());
        }


        The code above worked for me.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jan 9 at 12:21









        prabasprabas

        1816




        1816






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53994638%2fresponse-and-response-body-for-other-than-201-status-codes-not-found%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            MongoDB - Not Authorized To Execute Command

            How to fix TextFormField cause rebuild widget in Flutter

            in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith