I'm trying to post Json data to my Console. I have the code that is requesting it. I think I either have my Parameters or something else that is wrong. I know I get to the site, but then I get a 500 Server Error. I'm stuck and any help would be appreciated. I took out the URL and USER and Pass. I left the other stuff. I have no idea what I'm doing as I usually work with SQL, but I was told to try this and see if I can get it to work. We are using a Console app with the .NET framework to try and get this to work. Please help as I'm out of ideas. Something might be wrong with the headers.Accept code as well.
I've tried changing the code where my params are, I've tried even google and looking at other stack over flow methods.
public static void Main(string[] args)
{
try
{
string webAddr ="MYURL";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Accept = "application/Json";
using (var streamWriter = new
StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(new
{
USER_ID = "MyUser",
PASSWORD = "MyPass",
Query_ID = "4444",
Parameters = ""Key" ("Original"),"Value" ("1.1323")
});
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
Console.WriteLine("Here is your Json Data.....");
Console.WriteLine(responseText);
Console.ReadLine();
//Response success above and error below
}
}
catch (WebException ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
}
}
For the Json data to show up in the Console.
Related
Here is my code below. Getting the token from shopify works fine. However while creating a new product it keeps giving me an error. I've tried everything possible and it still does not work. Any advice would be appreciated.
Here's how I call the CreateNewProduct method passing the access token from shopify and the shopname with the products endpoint.
CreateNewProduct(accessTokenDTO.access_token, "https://{myshopname}.myshopify.com/admin/api/2020-10/products.json");
Here's the method below.
public static void CreateNewProduct(string token, string Url)
{
Uri shopUri = new Uri(Url);
HttpWebRequest GETRequest = (HttpWebRequest)WebRequest.Create(shopUri);
GETRequest.ContentType = "application/json";
GETRequest.Headers.Add("X-Shopify-Access-Token", token);
GETRequest.PreAuthenticate = true;
GETRequest.Method = "PUT";
using (var streamWriter = new StreamWriter(GETRequest.GetRequestStream()))
{
string json = "{\"product\": { \"title\": \"Burton Custom Freestyle 151\", \"body_html\": \"<strong>Good snowboard!</strong>\", \"vendor\": \"Burton\", \"product_type\": \"Snowboard\", \"tags\": [ \"Barnes & Noble\", \"John's Fav\", \"\\Big Air\\]}";
streamWriter.Write(json);
streamWriter.Flush();
}
HttpWebResponse GETResponse = (HttpWebResponse)GETRequest.GetResponse();
var encoding = ASCIIEncoding.ASCII;
using (var reader = new System.IO.StreamReader(GETResponse.GetResponseStream(), encoding))
{
string responseText = reader.ReadToEnd();
Debug.WriteLine("Response Text: " + responseText);
}
GETResponse.Close();
}
400 BadRequest normally refers to the body you are sending with your request is not valid according to the api.
Wheni look at your string that is supposed to be a json, it shows invalid data at the end.
[ \"Barnes & Noble\", \"John's Fav\", \"\\Big Air\\]}";
You are missing closing quotes after Big Air. Also, not sure if those backslash are supposed to be there around Big Air but definitely the missing closing quotes would seem to be the issue
There was an issue with the json not being formatted correctly and method was a PUT instead of POST. See working code below.
public static void CreateNewProduct(string token, string Url)
{
Uri shopUri = new Uri(Url);
HttpWebRequest GETRequest = (HttpWebRequest)WebRequest.Create(shopUri);
GETRequest.ContentType = "application/json";
GETRequest.Headers.Add("X-Shopify-Access-Token", token);
GETRequest.PreAuthenticate = true;
GETRequest.Method = "POST";
using (var streamWriter = new StreamWriter(GETRequest.GetRequestStream()))
{
string json = "{\"product\": { \"title\": \"Burton Custom Freestyle 151\", \"body_html\": \"<strong>Good snowboard!</strong>\", \"vendor\": \"Burton\", \"product_type\": \"Snowboard\"} }";
streamWriter.Write(json);
streamWriter.Flush();
}
HttpWebResponse GETResponse = (HttpWebResponse)GETRequest.GetResponse();
var encoding = ASCIIEncoding.ASCII;
using (var reader = new System.IO.StreamReader(GETResponse.GetResponseStream(), encoding))
{
string responseText = reader.ReadToEnd();
Debug.WriteLine("Response Text: " + responseText);
}
GETResponse.Close();
}
In my C# application I have a while loop that gathers a string from a Redis message queue and sends it to a listening server.
At every cicle the connection is opened with an HttpWebRequest Post method and the data is sent using a StreamWriter variable.
Problem is: after sending two strings the application freezes without returning any error, it just does nothing for maybe a minute, after that it works again correctly and continues its job for another couple strings, freeze and so on.
Debug shows the delay happens during the declaration of the StreamWriter variable.
Here is the core of the code:
// configure Redis
var redis = new RedisClient("127.0.0.1");
while (true)
{
// read from Redis queue
string json = redis.BRPop(30, "sensors_data");
//...
//URL DECLARATION
//...
try
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentLength = json.Length;
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Proxy = null;
SendDataAsync(json, url);
}
}
static async Task SendDataAsync(string json, string url)
{
try
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentLength = json.Length;
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Proxy = null;
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
try
{
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
Console.Write("Data Sent");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
catch (Exception err)
{
Console.Write(err.Message);
}
Console.WriteLine();
}
So the code actually works, just there is some strange huge delay where it comes to declare the StreamWriter. Does anyone have any idea? I don't know how to handle the problem.
EDIT
while (true)
{
i = 0;
// read from Redis queue
string json = redis.BRPop(30, "sensors_data");
try
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentLength = json.Length;
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Proxy = null;
using (StreamWriter streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
try
{
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
var response = httpWebRequest.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string reply=reader.ReadToEnd();
Console.WriteLine(reply);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
catch (Exception err)
{
Console.Write(err.Message);
}
Console.WriteLine();
}
Found the solution: Apparently it is necessary to get an answer from the server, after I added the httpWebRequest.GetResponse() and the following two lines I didn't find delays anymore.
Suggestion: it's better to use WebClient, it didn't give me any problem from the first try.
The new Dropbox API documentation is at:
https://blogs.dropbox.com/developers/2015/04/a-preview-of-the-new-dropbox-api-v2/
I'm trying to execute a simple metadata call, but am having very little success. Here's the code I'm using:
private void go()
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.dropbox.com/2-beta/files/get_metadata");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add("Authorization: Bearer xxxxxxxxxxxxxxxxxxx");
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"path\": \"/avatar_501.png\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
this.TextBox1.Text = result;
}
}
Any help would be massively appreciated!
If you try this code, you'll see the body of the 400 response, which tells you that text/json is not a valid Content-Type. I converted your code to a console app, and I'm using Newtonsoft.Json for the JSON serialization. Otherwise, the only difference between your code and mine is the addition of exception handling to get the body of the 400.
class Program
{
static void Main(string[] args)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.dropbox.com/2-beta/files/get_metadata");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add("Authorization: Bearer <REDACTED>");
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(JsonConvert.SerializeObject(new {
path = "/avatar_501.png"
}));
}
HttpWebResponse response;
try
{
response = (HttpWebResponse)httpWebRequest.GetResponse();
}
catch (WebException e)
{
response = (HttpWebResponse)e.Response;
}
Console.WriteLine("Status code: {0}", (int)response.StatusCode);
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
Console.WriteLine(streamReader.ReadToEnd());
}
Console.ReadLine();
}
}
The output is as follows:
Status code: 400
Error in call to API function "files/get_metadata": Bad HTTP "Content-Type" header: "text/json". Expecting one of "application/json", "application/json; charset=utf-8", "text/plain; charset=dropbox-cors-hack".
Changing the Content-Type to application/json causes the call to succeed.
I am new to C#. I tried all solutions to other questions and still i can't find what is wrong. My code is common in other answers but it seems to never send anything. I have tried in my own server and the company i'm working for server. I know this kind of answer has been answered many times before, but maybe i am missing something like others so this might be useful to someone besides me.
C# code:
var buttonSaveClicked = new MouseEventHandler((o, a) =>
{
var user_token = this.textApiKey.Text;
if (user_token.Length == 0) MessageBox.Show("API Key cannot be empty!", "API Key Error", MessageBoxButtons.OK, MessageBoxIcon.None);
var httpWebRequest = (HttpWebRequest) WebRequest.Create("http://localhost/networksWindows.php");
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"user_token\": \"batatas\", \"bata\": \"cook\"}";
System.Diagnostics.Debug.WriteLine(json);
streamWriter.Write(json);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
System.Diagnostics.Debug.WriteLine(result);
User user = JsonConvert.DeserializeObject<User>(result);
if (user.status == "error") MessageBox.Show("Invalid API Key. Please make sure you have generated a API key and insert it correctly.", "API Key Error", MessageBoxButtons.OK, MessageBoxIcon.None);
else if (user.status == "success")
{
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(ThreadProc));
t.Start();
this.Close();
}
}
});
PHP script in my server:
<?php
$json = null;
if (isset($_POST['user_token']))
{
$json = $_POST['user_token'];
echo "user";
}
?>
If you want $_POST to understand your data, it has to be sent as form-encoded key=value&key2=value2, not as JSON.
If you want to post JSON, you need to decode it on server side:
$post = (array)json_decode(file_get_contents("php://input"));
if (isset($post['user_token'])) {
// ...
}
You can replace file_get_contents("php://input") with $HTTP_RAW_POST_DATA, but its availability depends on configuration.
P.S. streamWriter.Flush() call is redundant.
You have to decode your json post in PHP.
Try using this:
$json = json_decode($_POST);
if (isset($json['user_token']) {
$userToken = $json['user_token'];
}
Decode your json as an array:
$json = json_decode($_POST, true);
I've been trawling the answers in SO concerning posting a score to a Facebook app, and I still can't get it to work. The code I'm using is here -
private const string FACEBOOK_POST_SCORE_URL = "https://graph.facebook.com/me/scores?access_token={0}";
public void PostScoreAsync(Action<FacebookResponse> response, FacebookScore score)
{
try
{
// Append the user's access token to the URL
Uri fullUri = new Uri(string.Format(FACEBOOK_POST_SCORE_URL, AccessToken));
string json = JsonConvert.SerializeObject(score);
var request = (HttpWebRequest)WebRequest.Create(fullUri);
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(json);
}
request.BeginGetResponse(WebRequestCallback, new FacebookResult
{
Request = request,
Response = response
});
}
catch (ThreadAbortException)
{
throw;
}
catch (WebException ex)
{
if (response != null)
response(FacebookResponse.NetworkError);
}
catch (Exception ex)
{
if (response != null)
response(FacebookResponse.OtherError);
}
}
We're using webViews rather than iOS / Android Facebook SDKs, as we're building a cross-platform app in Mono.
Obviously I have the access token & the app appears to have full permissions to do what I want to do, which I allowed after login. Any thoughts appreciated!
I eventually found out (from a colleague) that the Facebook graph api won't take json encoded parameters, so we sorted it like so -
string parameters = "score=" + score.Score;
var request = (HttpWebRequest)WebRequest.Create(fullUri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(parameters);
}
Now it works fine - hopefully this'll help someone else not have the same problem.