Error message when posting to php from C# - c#

I want to post variables from C# to a php-script on my webserver. I tried this following code from the internet but it returns this error message:
Error: The remote server returned an error. (406) Not Acceptable.
The c# part:
string URI = "https://myserver.com/post.php";
string myParameters = "param1=value1&param2=value2";
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string HtmlResult = wc.UploadString(URI, myParameters);
MessageBox.Show(HtmlResult);
}
The php part:
<?php
if(isset($_POST['param1']) && isset($_POST['param2']))
{
$user = $_POST['param1'];
$date = $_POST['param2'];
echo $user . ' : ' . $date;
}
?>
I have tested it with a test post server and it works but it won't work on my server.

Your backend service is saying that the response type it is returning is not provided in the Accept HTTP header in your Client request.
Source: What is "406-Not Acceptable Response" in HTTP?

Related

403 Forbidden error while invoking API in c# code

This API is working through postman.
I am trying the same thrid-party API from my application like below:
string requestUrl = string.Empty;
string result = string.Empty;
System.Net.WebClient client = new System.Net.WebClient();
using (client)
{
requestUrl = "https://api.fyndx1.de/hogwarts/aggregators/api/v1/config1/authToken";
client.QueryString.Add("username", "tester");
client.QueryString.Add("password", "pwd123");
result = client.DownloadString(requestUrl);
}
403 error is coming. I tried to add User agent to header parameters after querystring but no use.
client.Headers.Add("User-Agent: Other");
Any help is appreciated. Thanks.

Minecraft authentication servers returning 403 forbidden

So, I'm trying to create a new authToken by sending a POST Request via C# to the minecraft authentication servers (https://authserver.mojang.com/authenticate), but im getting the following error:
System.Net.WebException: 'The remote server returned an error: (403) Forbidden.'
My current code to try and send the request is:
public void ObtainAccessToken(string username, string password)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://authserver.mojang.com/authenticate");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"agent\":{\"name\":\"Minecraft\",\"version\":1},\"username\":\"" + username + "\",\"password\":\"" + password + "\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
}
from: https://stackoverflow.com/a/28591279/17371073
I'm trying to log into an migrated account
Using my Java implementation from a few years back as a reference, the only difference I see is that I've added Content-Charset UTF-8 and Content-Length with the written payload byte size to the request header (that is, the byte size of the json string that you write). I suspect that I would have never done this if this wasn't necessary.
Edit: Following HTTP specification, your request is only valid if you either:
Include the Content-Length property in your HTTP header.
Close the connection directly after sending the HTTP request.
Since you are waiting for a response, you'll have to use the first option.

Python urllib with proxy not working while C# works

I am trying to get data from an API using python 'urllib.request'. My requests sometime need to post json data.
My network is behind a proxy
When i try to get the data using C# code, everything works great:
WebClient wc = new WebClient();
WebProxy wp = new WebProxy("{IP}", 8080);
wc.Proxy = wp;
var request = "https://{API address and params}";
Uri serviceUri = new Uri(request);
string download = wc.DownloadString(serviceUri);
My python code is:
import urllib
address = "https://{API address and params}"
req = urllib.request.Request(address)
req.set_proxy("{IP}:8080", "http")
response = urllib.request.urlopen(req)
My python code throws a 400 error code exception - 'bad request'
What am i doing wrong?

Post data to php

I ran into a problem lately:
C# code:
string URI = "http://cannonrush.tk/UpdateLogFile.php";
string myParameters = "text=test123";
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string HtmlResult = wc.UploadString(URI, myParameters);
Console.WriteLine(HtmlResult);
}
PHP file:
<?php
if (isset($_GET['text'])) {
$file = "LogFile.txt";
$handle = fopen($file, 'a') or die('ERROR: Cannot write to file: ' . $file);
date_default_timezone_set('Europe/Amsterdam');
$data = '~ ' . date('l jS \of F Y h:i:s A') . '>> ' . $_GET['text'] . "\n\n";
fwrite($handle, $data);
fclose($handle);
echo "SUCCESS";
} else {
echo "ERROR: Access forbidden without text";
}
?>
Now, whenever I run the above C# code, I get this output printed:
ERROR: Access forbidden without text
I have tried numerous versions to post data from C# to php, but nothing seems to work.
Any ideas?
Change $_GET["text"] to $_POST["text"] in the php file, or use DownloadString() instead of UploadString() in your C# code.
$_GET is only populated in GET requests, so UploadString will not work:
Uploads the specified string to the specified resource, using the POST method.
If you want to allow either verb, use $_REQUEST instead.

Unable to post a share using Jive REST API - getting 400 Bad Request error

I am trying to post a share on Jive using the /Shares REST API in .net using C#. However I am not able to do this and getting the following error:
"The remote server returned an error: (400) Bad Request."
Following is the code which I have written:
string response = string.Empty;
using(WebClient client = new WebClient())
{
string strJiveShareURL = "https://<JiveURL>";
strJiveShareURL += "/api/core/v3/shares";
var SharedJSON = new AddShareJSON
{
participants = new string[] {"https://<JiveURL>/api/core/v3/people/{username}" },
shared = "https://<<Content URL to be shared>>",
content= new Content
{
type = "text/html",
text = "This is a test share from SharePoint to Jive"
}
};
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string shareJSON = serializer.Serialize(SharedJSON);
Console.WriteLine("Setting Credentials:");
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes("UID:PWD"));
client.Headers[HttpRequestHeader.Authorization]= "Basic " + credentials;
client.Headers[HttpRequestHeader.Accept] = "application/json";
client.Headers[HttpRequestHeader.ContentType] = "application/json";
//BypassCertificateError();
response = client.UploadString(strJiveShareURL, "POST", shareJSON);
Console.WriteLine("Response:" + response);
Console.ReadLine();
}
and following is the JSON which is created for posting the share:
{
"content": {
"type":"text/html",
"text":"This is a test share from SharePoint to Jive"
},
"participants": ["https://<<Jive URL>>/api/core/v3/people/<<username>>"],
"Shared":"https://<<URL of the Content To be Shared>>"
}
Please let me know if there is anything which I have been doing incorrectly.
I figured this out myself, I was getting the error because I was passing an invalid URI object to the shared parameter of the Share REST endpoint. The shared parameter requires a content URI in the form of
http://[[JiveURL]]/api/core/v3/contents/[[ContentID]]
Earlier I was trying to pass URLs external to Jive resulting in the bad request error.

Categories

Resources