简体   繁体   中英

Send a POST request on Windows 8 metro App with C#

I try to make a POST request for a long time with C# but it never works.
The statusCode from the server is 200 so it seems to work but the response I get is an "AccessDenied". The HTTP header seems to be the error.
The POST request made on JS works great but not the one on C#.
Here is the request :

string resourceAddress = " ... ";
try
{
     HttpClient httpClient = new HttpClient();  
     var content = new List<KeyValuePair <string,string>>
     {
       new KeyValuePair<string,string>(" ... "," ... "),
         ...
     };

     HttpResponseMessage response = await httpClient.PostAsync(resourceAddress, new FormUrlEncodedContent(content));
     response.EnsureSuccessStatusCode();
     var responseString = await response.Content.ReadAsStringAsync(); 
}

catch (HttpRequestException hre)   
{
      Debug.WriteLine(hre.ToString());
}

catch (Exception ex)   
{
      Debug.WriteLine(ex.ToString());
}

Did I miss something ?
Does windows 8 with C# request modify or add something into the header ?

On Android I use this code :

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urlWebSiteHTTPRequest);

try
{           
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("... ","... "));
    ....
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    response = httpclient.execute(httppost);
    entity = response.getEntity();
    responseText = EntityUtils.toString(entity);
}   
catch (ClientProtocolException e) 
{
    // TODO Auto-generated catch block
} 
catch (IOException e) 
{
    // TODO Auto-generated catch block
}

I think the header is not properly formatted. Try using this simple tool. You will be able to use it to debug http request messages and actually see the data and errors the server sends back. http://www.telerik.com/fiddler . Go to the composer tab to test request messages. Also make sure that your Authorization username:password are base64 encoded. That always seems to be the problem in most cases.

Best of Luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM