HTTP Request in Xamarin - 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();

Related

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

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.

How to make jira attachments download work using jira rest api

I am trying to download attachments from Jira. I use /rest/api/2/attachment/{id} to get json response of the attachment. It has field "content" that is the attachment url. I use this url and construct HttpGet and execute to get response that always gives me html content asking for login. I am sending Basic Authorization in the httpGet header. Apparently this works for downloading .png files but not any other file types. I am using java spring rest to connect to Jira horizon.
Closeable httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(jira attachmenturl);
httpGet.setHeader("Authorization", "Basic <base64Credentials>);
CloseableHttpResponse response = httpclient.execute(httpGet)
The response for .txt, .jpeg, Microsoft documents is different from response that I get for .png files.
This works:
#GetMapping(value = "/getAttachment")
public String getAttachment(#RequestParam("id") String attachmentID) throws Exception {
Client client = Client.create();
WebResource webResource = client.resource(jiraBaseURLRest + "attachment/" +
attachmentID);
ClientResponse response = webResource.header("Authorization", "Basic " +
base64Creds).type("application/json")
.accept("application/json").get(ClientResponse.class);
String result = response.getEntity(String.class);
JSONObject jsonObj = new JSONObject(result);
System.out.println("JSON Object = "+jsonObj);
URL url = new URL(jsonObj.getString("content"));
Closeable httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url.toURI());
httpGet.setHeader("Authorization", "Basic " + base64Creds);
CloseableHttpResponse response1 = ((CloseableHttpClient) httpclient).execute(httpGet);
if(response1.getStatusLine().getStatusCode() == 200)
{
HttpEntity entity = response1.getEntity();
if (entity.isStreaming())
{
System.out.println("Streaming...");
byte data[] = EntityUtils.toByteArray(entity);
FileOutputStream fout = new FileOutputStream(new File("D://pdf1.pdf"));
fout.write(data);
fout.close();
System.out.println("Done!!");
}
}
return "Success";
}

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/

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"));
}

Cannot get cookies in wp7 using HttpWebRequest

I'm trying to save cookies in a post request. Here is my code :
CookieContainer myCookieContainer = new CookieContainer();
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
myHttpWebRequest.UserAgent = userAgent;
myHttpWebRequest.CookieContainer = myCookieContainer;
myHttpWebRequest.Method = "POST";
byte[] postdata = encoding.GetBytes(submitString);
myHttpWebRequest.BeginGetRequestStream(async1 =>
{
using (Stream stream = myHttpWebRequest.EndGetRequestStream(async1))
stream.Write(postdata, 0, postdata.Length);
myHttpWebRequest.BeginGetResponse(async2 =>
{
HttpWebResponse rep = (HttpWebResponse)myHttpWebRequest.EndGetResponse(async2);
CookieCollection cookies = rep.Cookies;
using (Stream stream = rep.GetResponseStream())
using (StreamReader sr = new StreamReader(stream))
{
String content = sr.ReadToEnd();
if (pageDownloadedEventHandler != null)
pageDownloadedEventHandler(content);
}
}, null);
}, null);
Alaways the CookieContainer is empty.
How to get the cookies?
Your code seems to be perfect, if the server sends you back any cookies you should see them in rep.Cookies, as well as in myCookieContainer.
If you want to be sure use Fiddler or Wireshark to analyze the HTTP network traffic and look for the cookies, but if I'm right you won't find them. In this case my idea is to analyze the network traffic doing the same request with your browser, maybe the php/asp.net/other app decided not to set cookies due to some missing request headers.

Resources