I'm trying to do something that seems like it should be simple: to send a JSON request to a PHP script on my webserver and get the response.
I can request the site without issue, I can read the response without issue, but for some reason this refuses to send the contents of my JSON data.
string url = "https://www.exampleserver.com/examplescript.php";
HttpClient client = new HttpClient(new Xamarin.Android.Net.AndroidClientHandler());
client.BaseAddress = new Uri(url);
string jsonData = #"{""key1"" : ""data1"",""key2"" : ""data2"",""key3"" : ""data3""}";
HttpContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(url, content);
string result = await response.Content.ReadAsStringAsync();
responsebox.Text = result;
Each time I run it the contents of responsebox.Text is replaced with the default contents of the page pointing out explicitly that there was no content in the $_POST data. (Even checked $_REQUEST to make sure it wasn't showing up as GET).
I know it's gotta be something simple, but I can't find it.
Related
Hello Stackoverflow community. I hope someone here can help me!!
I'm trying to integrate with the Zoopla API that requires the post request to send the following customized content type. (I've got the certificate side of things working fine).
application/json;profile=http://realtime-listings.webservices.zpg.co.uk/docs/v1.2/schemas/listing/list.json
I've tried the following approaches without any success (they all result in the following error)
System.FormatException: 'The format of value 'application/json;profile=http://realtime-listings.webservices.zpg.co.uk/docs/v1.2/schemas/listing/list.json' is invalid.'
Initial approach was to set it within the content of the RequestMessage
var request = new HttpRequestMessage()
{
RequestUri = new Uri("https://realtime-listings-api.webservices.zpg.co.uk/sandbox/v1/listing/list"),
Method = HttpMethod.Post,
Content = new StringContent(jsonBody, Encoding.UTF8, "application/json;profile=http://realtime-listings.webservices.zpg.co.uk/docs/v1.2/schemas/listing/list.json")
};
When that didn't work I tried to set it via the default headers (the client below is from the ClientFactory)
client.DefaultRequestHeaders.Add("Content-Type", "application/json;profile=http://realtime-listings.webservices.zpg.co.uk/docs/v1.2/schemas/listing/list.json");
My final attempt was to set it without validation
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json;profile=http://realtime-listings.webservices.zpg.co.uk/docs/v1.2/schemas/listing/list.json");
I've just tried something else which unfortunately didn't work
string header = "application/json;profile=http://realtime-listings.webservices.zpg.co.uk/docs/v1.2/schemas/listing/list.json";
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue(header));
I am well and truly stumped!! HELP!! :-)
Content-Type is set on the content, not in DefaultRequestHeaders. You may try using TryAddWithoutValidation on the request content:
var content = new StringContent("hello");
content.Headers.ContentType = null; // zero out default content type
content.Headers.TryAddWithoutValidation("Content-Type", "application/json;profile=http://realtime-listings.webservices.zpg.co.uk/docs/v1.2/schemas/listing/list.json");
var client = new HttpClient(); // note: use IHttpClientFactory in non-example code
var response = await client.PostAsync("https://postman-echo.com/post", content);
Console.WriteLine(response.StatusCode); // OK
Console.WriteLine(await response.Content.ReadAsStringAsync());
// {"args":{},"data":{},"files":{},"form":{},"headers":{"x-forwarded-proto":"https","x-forwarded-port":"443","host":"postman-echo.com","x-amzn-trace-id":"Root=1-6345b568-22cc353761f361483f2c3157","content-length":"5","content-type":"application/json;profile=http://realtime-listings.webservices.zpg.co.uk/docs/v1.2/schemas/listing/list.json"},"json":null,"url":"https://postman-echo.com/post"}
I'm trying to send an image to my server using a multipart data form, but whenever I attempt to send it I am timing out due to a lack of response. I am able to connect to the server when I try to post an HTTPContent object, but am having problems once I throw in MultiPartFormDataContent objects. I have tested the PHP code with an html form, so I know the problem lies in my Xamarin code
Xamarin Code:
MultipartFormDataContent Content = new MultipartFormDataContent();
HttpContent FileContent = new ByteArrayContent(Appointment.PicBytes);
Content.Add(FileContent, "AppointmentPicture", "AppointmentPicture");
HttpResponseMessage Response = await Client.PostAsync(Uri, Content);
string Details = await Response.Content.ReadAsStringAsync();
You could try this
string convertedImage = Convert.ToBase64String(data);
HttpContent content = new StringContent(convertedImage, Encoding.UTF8, "application/json");
I'm trying to consume data in my front-end which calls a API Broker and this API Broker calls my API. In my front-end I'm getting JSON data returned JSON with alot of backslashes in it. How can i prevent this? see code and errors below:
Consuming my API in my front-end:
[HttpGet]
public async Task<ActionResult> getCall()
{
string url = "http://localhost:54857/";
string operation = "getClients";
using (var client = new HttpClient())
{
//get logged in userID
HttpContext context = System.Web.HttpContext.Current;
string sessionID = context.Session["userID"].ToString();
//Create request and add headers
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//Custom header
client.DefaultRequestHeaders.Add("loggedInUser", sessionID);
//Response
HttpResponseMessage response = await client.GetAsync(operation);
if (response.IsSuccessStatusCode)
{
string jsondata = await response.Content.ReadAsStringAsync();
return Content(jsondata, "application/json");
}
return Json(1, JsonRequestBehavior.AllowGet);
}
}
My Api Broker gets the request and executes this:
As you can see the response content contains alot of backslashes.
This response is going back to my front-end where i receive the following content:
In this response there are even more backslashes added.
I hope someone recognizes this problem and knows a solution.
Thanks in advance!
I fixed it by serializing the string to a JSON object and than deserialize it .
Rest API is written and I have a URL of one method. I just want to hit that URL and add single key value pair in header, and json data in body. This is what I have done so far:
var client = new HttpClient();
client.BaseAddress = new Uri(uri);
client.DefaultRequestHeaders.Remove("authorization");
client.DefaultRequestHeaders.Add("authorization", "Token "+base64token);
var content = new StringContent(JsonString, Encoding.UTF8,
"application/json");
HttpResponseMessage response = await client.PutAsync(queryString, content);
Here uri= My base url, base64token= authorization token, JsonString= Json data for body, queryString= path of method called.
Now, problem is that this method works for the first time correctly for user1. But does'nt works for user2. And when I call again for user1, it is still working for user1. Kindly help
There is StringContent class in System.Net.Http namespace. What purposes should I use class StringContent for?
StringContent class creates a formatted text appropriate for the http server/client communication. After a client request, a server will respond with a HttpResponseMessageand that response will need a content, that can be created with the StringContent class.
Example:
string csv = "content here";
var response = new HttpResponseMessage();
response.Content = new StringContent(csv, Encoding.UTF8, "text/csv");
response.Content.Headers.Add("Content-Disposition",
"attachment;
filename=yourname.csv");
return response;
In this example, the server will respond with the content present on the csv variable.
It provides HTTP content based on a string.
Example:
Adding the content on HTTPResponseMessage Object
response.Content = new StringContent("Place response text here");
Whenever I want to send an object to web api server I use StringContent to add format to HTTP content, for example to add Customer object as json to server:
public void AddCustomer(Customer customer)
{
String apiUrl = "Web api Address";
HttpClient _client= new HttpClient();
string JsonCustomer = JsonConvert.SerializeObject(customer);
StringContent content = new StringContent(JsonCustomer, Encoding.UTF8, "application/json");
var response = _client.PostAsync(apiUrl, content).Result;
}
Every response that is basically text encoded can be represented as StringContent.
Html reponse is text too (with proper content type set):
response.Content = new StringContent("<html><head>...</head><body>....</body></html>")
On the other side, if you download/upload file, that is binary content, so it cannot be represented by string.