CodeLover
CodeLover

Reputation: 11

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?

Upvotes: 1

Views: 8361

Answers (2)

curt
curt

Reputation: 161

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();

Upvotes: 0

Wolfgang Schreurs
Wolfgang Schreurs

Reputation: 11834

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).

Upvotes: 2

Related Questions