1

I am sending a JSON request via http post. Backend requires me to send two headers, namely - Authorization and Content-Type. Then a raw JSON request as body. I send the request via Post method via Postman tool and the message gets through successfully. But when I send the same request with same headers via code, I get a bad request - Error.

I minimized the scope of testing to check. I have sent only the two headers via Postman and here's the response:

Headers

Authorization: "bearer " + token. The structure is "bearer" keyword + space + Okta token. Content-Type: application/json

Response:

Headers

Content-Type →application/json; charset=utf-8

Strict-Transport-Security →max-age=31536000

X-Content-Type-Options →nosniff

Request-Context →appId=cid-v1:dc220dda-e515-4dd4-b324-c078a1b8fac4

Date →Sun, 26 May 2019 13:23:01 GMT

Content-Length →29

Body { "Message": "No Request Body" }

But when I send the same thing via code, I get a Bad-Request Error. Please help :(

  HttpClient httpclient1;
  HttpPost httppost1;
  //ArrayList<NameValuePair> postParameters1 = null;
  httpclient1 = HttpClientBuilder.create().build
  httppost1 = new HttpPost(Constants.URL);

  //  httppost1.setEntity(new UrlEncodedFormEntity(postParameters1,"UTF-8"));
  //  httppost1.setEntity(new StringEntity(request,"UTF-8"));

  httppost1.setHeader("Authorization", token);
  httppost1.setHeader("Content-Type", "application/json");
  // httppost1.setHeader("Content-Length", strlength);
//   httppost1.setHeader("Accept", "application/json");

 //  StringEntity entity = new StringEntity(request,ContentType.APPLICATION_JSON);
 //  httppost1.setEntity(entity);

 HttpResponse response1 = httpclient1.execute(httppost1);
 InputStream is = response1.getEntity().getContent();

 HttpEntity entity1 = httppost1.getEntity();

 Header[] headers = httppost1.getAllHeaders();
 System.out.println(headers.length);
 for(int i=0; i<headers.length;i++)
 {
   System.out.println(headers[i]);
 }


String result = convertInputStreamToStringCommonIO(is);
System.out.println();
System.out.println(result);

int code1 = response1.getStatusLine().getStatusCode();
System.out.println("Code: "+code1+"");
String reason1 = response1.getStatusLine().getReasonPhrase();
System.out.println("Description: "+reason1 +"");

Temporary Request Headers from Postman:

UserAgent: PostmanRuntime/7.13.0

Accept: /

Cache-Contro: no-cache

Postman-Token: *****

Host: *****

accept-encoding: gzip,dflate

content-length:

Connection: keep-alive

Here's the error I am getting:

{"errorCode":"E0000021","errorSummary":"Bad request. Accept and/or Content-Type headers likely do not match supported values.","errorLink":"E0000021","errorId":"oae5BpTGp_5RjaFtGn_Zm_mhw","errorCauses":[]} Code: 400 Description: Bad Request

Any idea why it's failing via code? Thanks.

0 Answers0