Anyone knows how to send the request using JSON content in windowsphone. I had the JSON parameters how to post it.
Simply serialize the data in JSON, and write it as a POST request to the server. Here's how I do it in one of my apps:
private static IObservable<T> GetDataAsync<T, TRequest>(TRequest input, string address)
{
var request = HttpWebRequest.Create(address);
request.Method = "POST";
var getRequestStream = Observable.FromAsyncPattern<Stream>(
request.BeginGetRequestStream,
request.EndGetRequestStream);
var getResponse = Observable.FromAsyncPattern<WebResponse>(
request.BeginGetResponse,
request.EndGetResponse);
return getRequestStream()
.SelectMany(stream =>
{
try
{
using (var writer = new StreamWriter(stream))
writer.WriteLine(JsonConvert.SerializeObject(input));
}
catch
{
// Intentionally ignored.
}
return getResponse();
})
.Select(webResponse =>
{
using (var reader = new StreamReader(webResponse.GetResponseStream()))
return JsonConvert.DeserializeObject<T>(reader.ReadToEnd());
});
}
Related
We are getting 502 error when we try to send photo in Json.
App developed with .NET and Xamarin.Form
var jsonObjGuid = JsonConvert.SerializeObject(ObjGuid);
var jsonObjFiles = JsonConvert.SerializeObject(ObjFiles, Formatting.Indented);
var url = $"{ Session.EndpointURL}{MethodNames.UploadDossierFiles.Value}";
try
{
using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.TransferEncodingChunked = true;
httpClient.Timeout = TimeSpan.FromMilliseconds(600000);
using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url))
{
//request.Headers.Add(HeaderKeys.UserAgent.Value, Resources.DefaultUserAgent);
request.Headers.Add(HeaderKeys.UserAgent.Value, "MobileApp");
request.Headers.Add(HeaderKeys.Token.Value, token);
HttpContent ObjGuidContent = new StringContent(jsonObjGuid);
HttpContent ObjFilesContent = new StringContent(jsonObjFiles);
MultipartFormDataContent content = new MultipartFormDataContent
{
{ObjGuidContent, "ObjGuid"},
{ObjFilesContent, "ObjFiles"}
};
request.Content = content;
var response = await Policy.HandleResult<HttpResponseMessage>(message => !message.IsSuccessStatusCode)
.WaitAndRetryAsync(3, i => TimeSpan.FromSeconds(2), (result, timeSpan, retryCount, context) => { })
.ExecuteAsync(() => httpClient.SendAsync(request));
}
}
}
Sometimes it works but often I get this error.
Any help, suggestions? What do I need to check?
I am making an app which can upload image to a server (the server works well), and I use this method to upload my image to it, but when I get the respond from the result, it return a null string, can you explain for me what did I do wrong.
I followed this method: How to upload file to server with HTTP POST multipart/form-data
HttpClient httpClient = new HttpClient();
MultipartFormDataContent form = new MultipartFormDataContent();
form.Headers.ContentType = new MediaTypeHeaderValue("multipart/form-data");
byte[] bytes = await Converter.GetBytesAsync(storageFile);
form.Add(new ByteArrayContent(bytes, 0, bytes.Count()), "\"upload-file\"", "\"test.jpg\"");
HttpResponseMessage response = await httpClient.PostAsync("my-url", form);
response.EnsureSuccessStatusCode();
httpClient.Dispose();
string sd = response.Content.ReadAsStringAsync().Result;
Debug.WriteLine("res: " + sd); // this return a null string
The request return like this:
--a81d2efe-5f2e-4f84-83b9-261329bee20b
Content-Disposition: form-data; name="upload-file"; filename="test.jpg"; filename*=utf-8''%22test.jpg%22
����Ivg?�aEQ�.�����(��9%�=��>�C�~/�QG$�֨������(�`������QE��Z��
Can you help me please!
P/s: Here is my convert method
public static async Task<byte[]> GetBytesAsync(StorageFile file)
{
byte[] fileBytes = null;
if (file == null) return null;
using (var stream = await file.OpenReadAsync())
{
fileBytes = new byte[stream.Size];
using (var reader = new DataReader(stream))
{
await reader.LoadAsync((uint)stream.Size);
reader.ReadBytes(fileBytes);
}
}
return fileBytes;
}
This might help
private async Task<string> UploadImage(StorageFile file)
{
HttpClient client = new HttpClient();
MultipartFormDataContent form = new MultipartFormDataContent();
HttpContent content = new StringContent("fileToUpload");
form.Add(content, "fileToUpload");
var stream = await file.OpenStreamForReadAsync();
content = new StreamContent(stream);
content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "fileToUpload",
FileName = file.Name
};
form.Add(content);
var response = await client.PostAsync("my-url", form);
return response.Content.ReadAsStringAsync().Result;
}
Use ByteArrayContent instead of StringContent. That Should work.
And if you are expecting a stream-response you should use ReadAsStreamAsync instaed of ReadAsStringAsync.
I want to send file and json data from HttpClient to web api server.
I cant seem to access the json in the server via the payload, only as a json var.
public class RegulationFilesController : BaseApiController
{
public void PostFile(RegulationFileDto dto)
{
//the dto is null here
}
}
here is the client:
using (var client = new HttpClient())
{
using (var content = new MultipartFormDataContent())
{
client.BaseAddress = new Uri(ConfigurationManager.AppSettings["ApiHost"]);
content.Add(new StreamContent(File.OpenRead(#"C:\\Chair.png")), "Chair", "Chair.png");
var parameters = new RegulationFileDto
{
ExternalAccountId = "1234",
};
JavaScriptSerializer serializer = new JavaScriptSerializer();
content.Add(new StringContent(serializer.Serialize(parameters), Encoding.UTF8, "application/json"));
var resTask = client.PostAsync("api/RegulationFiles", content); //?ApiKey=24Option_key
resTask.Wait();
resTask.ContinueWith(async responseTask =>
{
var res = await responseTask.Result.Content.ReadAsStringAsync();
}
);
}
}
this example will work:HttpClient Multipart Form Post in C#
but only via the form-data and not payload.
Can you please suggest how to access the file and the submitted json And the file at the same request?
Thanks
I have tried many different ways to submit both file data and metadata and this is the best approach I have found:
Don't use MultipartFormDataContent, use only StreamContent for the file data. This way you can stream the file upload so you don't take up too much RAM on the server. MultipartFormDataContent requires you to load the entire request into memory and then save the files to a local storage somewhere. By streaming, you also have the benefit of copying the stream into other locations such as an Azure storage container.
This solves the issue of the binary data, and now for the metadata. For this, use a custom header and serialize your JSON into that. Your controller can read the custom header and deserialize it as your metadata dto. There is a size limit to headers, see here (8-16KB), which is a large amount of data. If you need more space, you could do two separate requests, one to POST the minimum need, and then a PATCH to update any properties that needed more than a header could fit.
Sample code:
public class RegulationFilesController : BaseApiController
{
public async Task<IHttpActionResult> Post()
{
var isMultipart = this.Request.Content.IsMimeMultipartContent();
if (isMultipart)
{
return this.BadRequest("Only binary uploads are accepted.");
}
var headerDto = this.GetJsonDataHeader<RegulationFileDto>();
if(headerDto == null)
{
return this.BadRequest("Missing X-JsonData header.");
}
using (var stream = await this.Request.Content.ReadAsStreamAsync())
{
if (stream == null || stream.Length == 0)
{
return this.BadRequest("Invalid binary data.");
}
//save stream to disk or copy to another stream
var model = new RegulationFile(headerDto);
//save your model to the database
var dto = new RegulationFileDto(model);
var uri = new Uri("NEW URI HERE");
return this.Created(uri, dto);
}
}
private T GetJsonDataHeader<T>()
{
IEnumerable<string> headerCollection;
if (!this.Request.Headers.TryGetValues("X-JsonData", out headerCollection))
{
return default(T);
}
var headerItems = headerCollection.ToList();
if (headerItems.Count() != 1)
{
return default(T);
}
var meta = headerItems.FirstOrDefault();
return !string.IsNullOrWhiteSpace(meta) ? JsonConvert.DeserializeObject<T>(meta) : default(T);
}
}
I have to send the cookies to server for every subsequent HTTPWebRequest. My code goes below.
class APIManager
{
CookieContainer cookieJar = new CookieContainer();
CookieCollection responseCookies = new CookieCollection();
private async Task<string> httpRequest(HttpWebRequest request)
{
string received;
using (var response = (HttpWebResponse)(await Task<WebResponse>.Factory
.FromAsync(request.BeginGetResponse, request.EndGetResponse, null)))
{
using (var responseStream = response.GetResponseStream())
{
using (var sr = new StreamReader(responseStream))
{
cookieJar = request.CookieContainer;
responseCookies = response.Cookies;
received = await sr.ReadToEndAsync();
}
}
}
return received;
}
public async Task<string> Get(string path)
{
var request = WebRequest.Create(new Uri(path)) as HttpWebRequest;
request.CookieContainer = cookieJar;
return await httpRequest(request);
}
public async Task<string> Post(string path, string postdata)
{
var request = WebRequest.Create(new Uri(path)) as HttpWebRequest;
request.Method = "POST";
request.CookieContainer = cookieJar;
byte[] data = Encoding.UTF8.GetBytes(postdata);
using (var requestStream = await Task<Stream>.Factory.FromAsync(request.BeginGetRequestStream, request.EndGetRequestStream, null))
{
await requestStream.WriteAsync(data, 0, data.Length);
}
return await httpRequest(request);
}
}
Every time i ask for the question people say that i have to set the cookie container with request by following code line.
request.CookieContainer = cookieJar;
and i used it but still server returns the 'token does not match' error. Do i need to talk to the vendor for it?
Following image shows my problem and requirement.
I haven't seen you do something with the cookieJar !
//Create the cookie container and add a cookie.
request.CookieContainer = new CookieContainer();
// This example shows manually adding a cookie, but you would most
// likely read the cookies from isolated storage.
request.CookieContainer.Add(new Uri("http://api.search.live.net"),
new Cookie("id", "1234"));
cookieJar in your APIManager is a member, everytime your instance APIManager, the cookieJar is a new instance. you need to make sure cookieJar contains what the website needs.
you can have a look at this How to: Get and Set Cookies
How do i read HttpRequest data sent by POST method from client, on the server, in Dart?
I send a message from the client like this:
HttpRequest request = new HttpRequest();
var url = "http://127.0.0.1:8081";
request.open("POST", url, async: false);
String data = 'hello from client';
request.send(data);
On server i am catching the request like this:
HttpServer.bind('127.0.0.1', 8081).then((server) {
server.listen((HttpRequest request) {
//DATA SHOULD BE READ HERE
});
});
But i cant figure out how to actually read the data... There is not data property in HttpRequest nor anything else...
EDIT This is how i get the answer now:
HttpServer.bind('127.0.0.1', 8081).then((server) {
server.listen((HttpRequest request) {
//DATA SHOULD BE READ HERE
print("got it");
print(request.method);
if(request.method == "POST") {
print("got it 2");
List<int> dataBody = new List<int>();
request.listen(dataBody.addAll, onDone: () {
var postData = new String.fromCharCodes(dataBody);
print(postData);
});
}
});
});
But for some reason the request.method is not "POST" but "OPTIONS", and if i change to if(request.method == "OPTIONS") , then print(postData) will still return nothing...
You can use the StringDecoder to tranform from "List of Int" to "String" from the HttpRequest. Since no matter if you send json, plain text, or png, Dart always send data in form of
"List of Int" to the server.Another means is to use the Streams (http://www.dartlang.org/articles/feet-wet-streams/) tested on Heroku Steam v0.6.2 Dart Editor 0.4.3_r20602 Dat SDK 0.4.3.5_r26062
For example,
the client:
import 'dart:html';
import 'dart:json' as Json;
import 'dart:async';
import 'dart:uri';
final String data = 'Hello World!';
void _sendPNG(String pngData) {
HttpRequest request = new HttpRequest(); // create a new XHR
// add an event handler that is called when the request finishes
request.onReadyStateChange.listen((_)
{
if (request.readyState == HttpRequest.DONE &&
(request.status == 200 || request.status == 0)) {
// data saved OK.
print(request.responseText); // output the response from the server
}
}
);
// POST the data to the server Async
print('Sending Photos to the server...');
var url = "/png";
request.open("POST", url);
request.setRequestHeader("Content-Type", "text/plain");
request.send(data);
}
the server:
import 'dart:io';
import 'dart:async';
import 'dart:json' as Json;
import "package:stream/stream.dart";
import 'package:xml/xml.dart' as xml;
import 'package:unittest/unittest.dart';
import 'package:rikulo_commons/mirrors.dart';
void receivePNG(HttpConnect connect){
var request = connect.request;
var response = connect.response;
if(request.uri.path == '/png' && request.method == 'POST')
{
String png='';
response.write('The server received png request!');
//read incoming List<int> data from request and use StringDecoder to transform incoming data to string
var stream = request.transform(new StringDecoder());
stream.listen((value){
print(value);
//Hello World!
}
else
{
response.write('error');
response.statusCode = HttpStatus.NOT_FOUND;
connect.close();
}
}
configure.dart
var _mapping = {
"/": home,
"/png": receivePNG,
};
Right now, the handling of POST data is a little difficult. But essentially the HttpRequest itself has to be 'listened' to. HttpRequest is a stream itself. In particular it's a Stream<List<int>>. So basically your data may be passed to your HttpRequest as multiple List<int>'s. So we need to reconstruct the data then convert it into a string (assuming you're expecting a string, not binary data, etc). Here's more or less what I do:
HttpServer.bind('127.0.0.1', 8081).then((server) {
server.listen((HttpRequest request) {
if(request.method == "POST") {
List<int> dataBody = new List<int>();
request.listen(dataBody.addAll, onDone: () {
var postData = new String.fromCharCodes(dataBody);
// Do something with the data now.
});
}
request.response.close();
});
Note that the request.listen(dataBody.AddAll, ...) basically calls List.addAll() each time data is to the server (in cases of larger data or multi-part forms it may not come all at once). This ensures we buffer it all until the stream indicates it is 'done' In which case we can now do something with the data we received, like convert it to a string.
I have found this useful example with client/side code
GitHub json send to server Example
// XXX: Dart Editor thinks this is OK, but I haven't run it.
import 'dart:html';
String encodeMap(Map data) {
return data.keys.map((k) {
return '${Uri.encodeComponent(k)}=${Uri.encodeComponent(data[k])}';
}).join('&');
}
loadEnd(HttpRequest request) {
if (request.status != 200) {
print('Uh oh, there was an error of ${request.status}');
return;
} else {
print('Data has been posted');
}
}
main() {
var dataUrl = '/registrations/create';
var data = {'dart': 'fun', 'editor': 'productive'};
var encodedData = encodeMap(data);
var httpRequest = new HttpRequest();
httpRequest.open('POST', dataUrl);
httpRequest.setRequestHeader('Content-type',
'application/x-www-form-urlencoded');
httpRequest.onLoadEnd.listen((e) => loadEnd(httpRequest));
httpRequest.send(encodedData);
}