I have some native android code which receives data back from the server which is then added to a JSONObject for later manipulation.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string responseStr = new StreamReader(response.GetResponseStream()).ReadToEnd();
JSONObject responseObj = new JSONObject(responseStr);
However, I'm moving this over to an mvvm framework so JSONObject can't be used (I'm also happier working with the much nicer JSON.NET libraries).
I've changed the JSONObject to JObject and come up with the following which compiles, but throws an exception on running (Cannot add a jtoken to a object)
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string responseStr = new StreamReader(response.GetResponseStream()).ReadToEnd();
var responseObj = new JObject(responseStr);
From what I've read, this should work (but is obviously isn't). Is there a way to store the responseStr as a JObject?
use JObject.Parse
var responseObj = new JObject.Parse(responseStr);
Related
I have an .net core WEB API method that needs to call another external API (java) which expects .zip file. When try to access the external API via Postman by attaching the file, it is working fine (getting expected response). However when i pass the same parameters via my WEB API code, it is throwing 403-Forbidden error.
Please let me know if i am missing anything....
Thanks in advance!!!
request-header
request-body-file-attached
response-403-error
API code: for connecting to api:
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("pane", "forward");
parameters.Add("forward_path", "/store/execute");
parameters.Add("csrf", "1996fe6b2d0c97a8a0db725a10432d83");
parameters.Add("data_format", "binary");
newContent = new FormUrlEncodedContent(parameters);
MultipartFormDataContent form = new MultipartFormDataContent();
HttpContent con;// = new StringContent("file_name");
//form.Add(con, "file_name");
form.Add(newContent);
var str = new FileStream("D:\\dummy\\xmlstore.zip", FileMode.Open);
con = new StreamContent(str);
con.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "file_name",
FileName = "xmlstore.zip"
};
con.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
form.Add(con);
client.DefaultRequestHeaders.Add("Cookie", "JSESSIONID=05DEB277E294CBF73288F2E24682C7EE;");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html"));
client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("deflate"));
client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("br"));
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("user-agent", "1"));
var resp = client.PostAsync("java-api", con).Result;
I'm writing a WebAPI for handling PDF documents. It was written in a ashx page earlier implementing IHttpHandler and getting the context using HttpContext. I'm now writing it using WebAPI. In WebAPI we have HttpResponseMessage. For HttpContext.Response.BinaryWrite we have new ByteArrayContent in HttpResponseMessage. But what is the alternative for HttpContext.Response.OutputStream in WebAPI? I need to have the alternative of OutputStram in WebAPI because im passing this OutputStream as a parameter to another dll.
Code in ashx:
SomeReport.PdfReport rpt = new SomeReport.PdfReport(docID);
rpt.CreateReport(context.Response.OutputStream);
Actually you can use any stream for example MemoryStream but result should be wrapped into StreamContent.
public HttpResponseMessage Get()
{
var response = Request.CreateResponse();
var outputStream = new MemoryStream();
//write data to output stream
//or passing it to somewhere
outputStream.WriteByte(83);
outputStream.Position = 0;
response.Content = new StreamContent(outputStream);
return response;
}
If you need direct writing to output stream, please consider using PushStreamContent. Example
I am implementing a Xamarin Form mobile app to allow post photo to Drupal using service module node resources. http://xxxx.com/{endpoint}/node/4/attach_file
i able to post from POSTMAN with
I tried to implement with c# HttpClient but keep getting response like "401 :Missing required argument field_name"
Please help on my code:
var httpClient = new HttpClient(new NativeMessageHandler());
httpClient.Timeout.Add(new TimeSpan(0, 0, 30));
httpClient.BaseAddress = new Uri(BaseAddress);
var content = new MultipartFormDataContent();
var streamContent = new StreamContent(g_media.GetStream());
streamContent.Headers.ContentDisposition = ContentDispositionHeaderValue.Parse("form-data");
streamContent.Headers.ContentDisposition.Parameters.Add(new NameValueHeaderValue("field_name", "field_receipt_image"));
content.Add(streamContent,"files[file]");
var response = await httpClient.PostAsync("node/4/attach_file", content);
response.EnsureSuccessStatusCode();
I had the same issue and used RestSharp to resolve it. Here is the code I used to upload a file to Drupal:
var restClient = new RestClient("http:XXXXXX/attach_file");
var request = new RestRequest(Method.POST);
request.AddFile("files[file]", fileName);
request.AddParameter("field_name", field);
IRestResponse response = restClient.Execute(request);
I have an ASP.NET MVC 5 website - in C# client code I am using HttpClient.PutAsJsonAsync(path, myObject) fine to call a Json API (the API is also mine created in Web API).
client.BaseAddress = new Uri("http://mydomain");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.PutAsJsonAsync("api/something", myObj);
I would like to do the same with a Delete verb. However client.DeleteAsync does not allow an object to be passed in the body. (I would like to record the reason for deletion alongside the Id of the item to delete in the URI).
Is there a way to do this?
You'll have to give up a little in terms of convenience since the higher-level DeleteAsync doesn't support a body, but it's still pretty straightforward to do it the "long way":
var request = new HttpRequestMessage {
Method = HttpMethod.Delete,
RequestUri = new Uri("http://mydomain/api/something"),
Content = new StringContent(JsonConvert.SerializeObject(myObj), Encoding.UTF8, "application/json")
};
var response = await client.SendAsync(request);
I have a Web Api service that retrieves data from another service, which returns Json. I don't want to do anything to the response, I just want to return it directly to the client.
Since the response is a string, if I simply return the response, it contains escape characters and messy formatting. If I convert the response in to an object, the WebApi will use Json.Net to automatically format the response correctly.
public IHttpActionResult GetServices()
{
var data = _dataService.Get(); //retrieves data from a service
var result = JsonConvert.DeserializeObject(data); //convert to object
return Ok(result);
}
What I would like is to either A: Be able to return the exact string response from the service, without any of the escape characters and with the proper formatting, or B: Set a global settings that will automatically Deserialize the response so that the Web Api can handle it the way I am doing it already.
On Startup I am setting some values that describe how formatting should be handled, but apparently these aren't correct for what im trying to do.
HttpConfiguration configuration = new HttpConfiguration();
var settings = configuration.Formatters.JsonFormatter.SerializerSettings;
settings.Formatting = Formatting.Indented;
settings.ContractResolver = new DefaultContractResolver();
Do I need to create a custom ContractResolver or something? Is there one that already handles this for me?
Thanks
If you want to just pass through the json (Option A), you can do this
public IHttpActionResult GetServices() {
var json = _dataService.Get(); //retrieves data from a service
HttpContent content = new System.Net.Http.StringContent(json, Encoding.UTF8, "application/json");
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = content;
return ResponseMessage(response);
}