Getting 502 BadGateway response when posting using HttpClient (.NET) but not when using Postman - http-post

I have an API end-point that I need to post to.
Using Postman I do the following:
Set the method to be POST
Add the URL
In the Headers I set: Content-Type to be application/json
In the Body I add my json string
I hit [Send] and get a 200 response with the expected response.
However, in C# .Net Framework 4.8 (LinqPad 5) I do
var c = new HttpClient(); // Disposed of later
c.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string data = #"{ ""a"": ""b"", ""c"": ""d"" }"; // copied from Postman.
HttpContent payload = new StringContent(data, Encoding.UTF8, "application/json");
var msg = new HttpRequestMessage(HttpMethod.Post, new Uri("https://the.url"), UriKind.Absolute)
{
Content = payload,
};
var response = c.SendAsync(msg).GetAwaiter().GetResult(); // It's a synchronous flow
And this responds with a 502 Bad Gateway.
What am I missing...?
I should point out that I need to use the HttpClient and not RestSharp.

Related

OkHttp response 204 with content-type json

When i use okhttp3 ver 4.7.2 to create a json request with third api, I will receive response 204. But when I use asyncHttpClient to create the same json request, I will receive correct data.
This is my code using okhttp3:
MediaType JSON = MediaType.get("application/json");
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
interceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);
OkHttpClient client = new OkHttpClient().newBuilder().addInterceptor(interceptor).build();
RequestBody body = RequestBody.create("{}", JSON);
Request request = new Request.Builder()
.url(URL).post(body).build();
System.out.println("Start");
okhttp3.Response response = client.newCall(request).execute();
System.out.println(response.body().string()); // null
System.out.println(response.code()); // 204
This is my code using asyncHttpClient:
ListenableFuture<org.asynchttpclient.Response> whenResponse = client
.preparePost(URL)
.addHeader("Content-Type", "application/json").setBody("{}").execute();
org.asynchttpclient.Response response = whenResponse.get();
System.out.println(response.getResponseBody()); // Correct response body
System.out.println(response.getStatusCode()); // 200
Request json send by okhttp have conten-type is application/json; charset=utf-8, third api allow only application/json. So their response 204.

Delete data from D365 in Batch Request, getting the error 'Content-Type' Header is missing

I am trying to create an Azure function to delete some data from a Dynamics 365 CE instance. The plan is to use the D365 WebAPI and the Batch Operations request to establish this.
Currently encountering an issue while sending a request after creating the batch request.
I have been referring to this documentation from Microsoft:
https://learn.microsoft.com/en-us/powerapps/developer/common-data-service/webapi/execute-batch-operations-using-web-api
The code looks like:
var batchId = Guid.NewGuid().ToString();
log.LogInformation($"Batch Request Id = {batchId}.");
HttpRequestMessage deleteBatchRequestMessage = new HttpRequestMessage(HttpMethod.Post, "$batch");
deleteBatchRequestMessage.Content = new MultipartContent("mixed", "batch_" + batchId);
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(d365Url);
// Default Request Headers needed to be added in the HttpClient Object
client.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
client.DefaultRequestHeaders.Add("OData-Version", "4.0");
client.DefaultRequestHeaders.Add("Prefer", "odata.include-annotations=\"OData.Community.Display.V1.FormattedValue\"");
d365HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Set the Authorization header with the Access Token received specifying the Credentials
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", d365Token);
HttpResponseMessage response = await client.SendAsync(deleteBatchRequestMessage);
var ass = await response.Content.ReadAsStringAsync();
But I keep getting the exception:
The 'Content-Type' header is missing. The 'Content-Type' header must be specified for each MIME part of a batch message.","ExceptionMessage":"The 'Content-Type' header is missing. The 'Content-Type' header must be specified for each MIME part of a batch message."
Is there any reason why you use WebApi? You can use the SDK and the IOrganizationService handle Everything. This will make your life very easy
http://www.threadpunter.com/azure/using-azure-functions-to-call-dynamics-365/

Invalid mimetype exception in Spring boot rest call

I am new to both Spring boot and rest calls.
I am trying to consume a rest service and I do not have any information about that rest API except URL. When I hit that URL from a browser I am getting a response as {key:value}. So, I assumed that it is a JSON response.
I am consuming it in spring boot as follows
restTemplate.getForObject(url, String.class) .
This is giving Invalid mime type "content-type: text/plain; charset=ISO-8859-1": Invalid token character ':' in token "content-type: text"
I assume that this error is because response content type is set to text/plain but it is returning JSON format.
EDIT:
Tried this way but did not work.
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>("parameters",headers);
ResponseEntity<String> result = restTemplate.exchange(url,HttpMethod.GET,
entity, String.class);
How to handle and solve it?
You might want to read about the request headers your REST API needs. Content-Type header specifies the media type of the request you're sending to the server. Because you're just getting data from the server you should set the Accept header to the kind of response you want i.e., Accept: application/json.
Unfortunately, you can't set headers using getForObject(). You could try this:
URL url = new URL("Enter the URL of the REST endpoint");
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "application/json");
if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuffer content = new StringBuffer();
String inputLine;
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
}

Google RECAPTCHA always returning error missing-input-response in the response

Google RECAPTCHA always returning error missing-input-response in the response when I try to check the correctness. How does the call to the service go, to the URL https://www.google.com/recaptcha/api/siteverify ?
The format is:
https://…/api/siteverify?secret=[…]&response=[…]&remote_ip=[…]
Make sure that Content-Type is set to application/x-www-form-urlencoded
.Net example
using (HttpClient httpClient = new HttpClient())
{
var response = await httpClient.PostAsync(GoogleVerificationUrl + "?secret=" + ReCaptchaSecretKey + "&response=" + ReCaptchaResponse, new StringContent("", Encoding.UTF8, "application/x-www-form-urlencoded"));
}

HTTP Request in Xamarin

I wrote the following code in Xamarin to connect the Web Server:
var request = WebRequest.Create( "http://srv21.n-software.de/authentication.json") as HttpWebRequest;
// request.Method = "GET";
request.Method = "POST";
request.Headers.Add("name", "demo");
request.Headers.Add("password", "demo");
request.ContentType = "application/x-www-form-urlencoded";
HttpWebResponse Httpresponse = (HttpWebResponse)request.GetResponse();
It connects to the web server and the web server gets the request for "authentication.json", but doesn't get the parameters of the header ("name" and "password").
What is wrong with my code?
Most likely your parameters need to be in the body of the POST request instead of in the headers. Alternatively you might try to use a GET request instead and provide the parameters through the URL, if your server supports it (i.e. http://srv21.n-software.de/authentication.json?name=demo&password=demo).
This worked for me
using System.Net.Http;
string URL = "http://www.here.com/api/postForm.php";
string DIRECT_POST_CONTENT_TYPE = "application/x-www-form-urlencoded";
HttpClient client = new HttpClient();
string postData = "username=usernameValueHere&password=passwordValueHere");
StringContent content = new StringContent(postData, Encoding.UTF8, DIRECT_POST_CONTENT_TYPE);
HttpResponseMessage response = await client.PostAsync(DIRECT_GATEWAY_URL, content);
string result = await response.Content.ReadAsStringAsync();

Resources