I'm having problems trying to do a GET request to Parse REST API using RestSharp.Portable in a PCL Xamarin project.
The problem occurs in the line:
var result = await client.Execute (request);
Throwing an exception and stopping the app (Android).
This is the function i'm using.
public async Task<EventItem> GetAListOfAllEvents ()
{
using (var client = new RestClient (new Uri ("http://api.parse.com"))) {
var request = new RestRequest ("1/classes/Event/2yHLWDUlv3");
request.Method = HttpMethod.Get;
request.AddHeader ("Content-Type", "application/json");
request.AddHeader ("X-Parse-Application-Id", "myAppId");
request.AddHeader ("X-Parse-REST-API-Key", "myAPIparseKey");
var result = await client.Execute (request);
return result;
}
}
I hope someone could help me, thanks.
Remove this line.
request.AddHeader ("Content-Type", "application/json");
Request is failing because of it (probably as you have no actual content in your GET request).
Related
I need to send a multipart request.
When I am submitting the form I am getting below error from backend,
Resolved exception caused by Handler execution: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/octet-stream' not supported
I am able to hit from Advanced rest client, but facing issue with angular.
On backend side below is The REST endpoint.
#PostMapping("/createCIF")
public Response < Map < String, Object >> createCIF(
#RequestPart("actDocs") List < MultipartFile > actDocs,
#Valid #RequestPart("createCIFReq") CreateCIFReq createCIFReq,
HttpServletRequest request) throws URISyntaxException {
}
Below is the angular side code in component.ts file.
let formData = new FormData();
formData.append('actDocs', this.userInfoService.mulitPartFileArray);
formData.append('createCIFReq', JSON.stringify(this.userInfo));
this.userInfoService.createCif(formData)
.pipe(first())
.subscribe(
data => {
}
}
Angular side Service level code
createCif(formData): any {
return this.http.post<any>(this.url + 'createCIF',
formData)
.pipe(map(cif => {
return cif;
}));
}
I got stuck on this issue an entire day.
Angular seems to fail to set a correct content-type to the JSON part.
I managed to solve this by creating a Blob :
let formData = new FormData();
formData.append('actDocs', this.userInfoService.mulitPartFileArray);
formData.append(
'createCIFReq',
new Blob([JSON.stringify(this.userInfo)], {type: 'application/json'})
);
Hope it helps.
I'm using an express api (my back-end) and an angular app (my front-end).
One express js end point (let's call it '/foo') is processing a lot of files,
i send data using res.write() after each treatment so the http response body is update.
I would like to get this update on my angular app.
I was using ajax in a previous version and it worked fine with ajax call :
xhrFields: {
// Getting on progress streaming response
onprogress: function(e)
{
var progressResponse;
var response = e.currentTarget.response;
if(lastResponseLength === false)
{
progressResponse = response;
lastResponseLength = response.length;
}
else
{
progressResponse = response.substring(lastResponseLength);
lastResponseLength = response.length;
}
actualResponse += progressResponse
}
Unfortunatly i found nothing to get partial http body. I tried to use 'reportProgress' Parameter but it's not working.
For some more context my front-end angular code:
service.ts :
setHolidaysDirectory(holidaysKey: string, path: string): Observable<Object>{
const setHolidayDirectoryStreamHttpRequest =
new HttpRequest('POST', 'http://localhost:8089/holidays/pictures/edit', { 'key': holidaysKey,
'path': path
}, {headers: this._httpHeaders, reportProgress: true, responseType: 'text'});
// pipe stream answer
return this._http.request(setHolidayDirectoryStreamHttpRequest);
}
and my component just call the service and subscribe :
this._holidaysService
.setHolidaysDirectory(key, finalHolidaysForm.path)
.subscribe((stream) => {
console.log('new answer');
console.log(stream);
}, error => console.log(error));
But unfortunatly i got empty answer and all the http body is recovered after res.end() (server side)
Can anyone help pls !
Thank a lot !
i am trying to call web Api that returns a list of object but it always throws an error : Internal Server Error
my code as below:
Web API
// GET: api/UploadFileStructures
[ResponseType(typeof( IEnumerable<UploadFileStructure>))]
public IHttpActionResult GetUploadFileStructuresByMovieId(int MovieDetailId)
{
IEnumerable<UploadFileStructure> uploaFileStructures= db.UploadFileStructures.Where(u=>u.MovieDetailId== MovieDetailId).AsEnumerable();
return Ok(uploaFileStructures);
}
Http Request:
using (var client = new HttpClient(handler))
{
//client.BaseAddress = UsersLogin;
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetAsync(String.Format(GetUploadFileStructuresByMovieIdUrl, MovieDetailId)).Result;
if (response.IsSuccessStatusCode)
{
UploadFileStructureDtls= response.Content.ReadAsAsync<IQueryable<UploadFileStructure>>().Result;
}
}
response.IsSuccessStatusCode is returing false and response returning " Internal Server Error"
The problem is on this line of your server code:
IEnumerable<UploadFileStructure> uploaFileStructures= db.UploadFileStructures.Where(u=>u.MovieDetailId== MovieDetailId).AsEnumerable();
If you set a breakpoint there, you should be able to see the actual error message that is generated.
I am trying to upload a file to the REST Api of Octoprint, which should be done by sending a POST request with Content-Type: multipart/form-data
(http://docs.octoprint.org/en/master/api/fileops.html#upload-file)
I am using NodeJS and two libraries, XmlHttpRequest and form-data. When trying:
var xhr = new xmlhttprequest() ;
var form = new formData() ;
form.append('exampleKey', 'exampleValue');
xhr.open("POST","octopi.local/api/local", true) ;
xhr.setRequestHeader("Content-Type","multipart/form-data") ;
xhr.send(form) ;
I get an error at the xhr.send line :
TypeError: first argument must be a string or Buffer
If I make a synchronous request by using xhr.open("POST",url,false), this error disappears.
Why is it so ? Is there a way to turn it into an asynchronous request ?
EDIT Actually, I don't really understand the documentation. I suppose that I should set the file I want to upload by using form.append("filename", filepath, "exampleName"), but I am not sure about that. The fact is that I noticed that I get the TypeError even if I try a simplified request, without sending any file.
EDIT2 This is the modified code, which returns the same error :
var XMLHttpRequest=require('xmlhttprequest').XMLHttpRequest ;
var FormData = require('form-data');
var data = new FormData();
data.append("key","value" );
var xhr = new XMLHttpRequest();
xhr.open('POST', "octopi.local/api/files/");
xhr.send(data);
After a long time working on this, I finally managed to upload a file. If you use NodeJS, don't rely on the MDN documentation: it tells what the libraries should do, not what they can actually do on the node platform. You should only focus on the docs available on GitHub.
It seems that it is not currently possible to send a form with XMLHttpRequest : I tried using JSON.stringify(form) but then wireshark tells me that the request is not a multipart/formdata request.
If you want to upload a file, you should rather use the 'request' module. The following has worked for me :
exports.unwrappeduploadToOctoprint = function(){
"use strict" ;
var form ={
file: {
value: fs.readFileSync(__dirname+'/test2.gcode'),
options: { filename: 'test2.gcode'}
}
};
var options = {
method: 'POST',
url: 'http://192.168.1.24/api/files/local',
headers: { 'x-api-key': 'E0A2518FB11B40F595FC0068192A1AB3'},
formData: form
};
var req = request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
};
Seems that you have some typos in your code. Use code snippet below instead. Replace the relevant parts according to your needs
var fileToUpload = document.getElementById('input').files[0];
var data = new FormData();
data.append("myfile", fileToUpload);
var xhr = new XMLHttpRequest();
xhr.open('POST', "upload_endpoint");
xhr.send(data);
I'm working on Windows phone client for one service with Oauth1 API.
In API docs I have something like this:
url: http://example.com/iphone/json/users/
method: GET
parameters:
page_num=[int] - page number, >=1, default=1.
For default page num everything works well:
RestClient HabraClient = new RestClient("http://habrahabr.ru");
HabraClient.Authenticator = OAuth1Authenticator.ForProtectedResource("xxx", "yyyyyy", App.Tokens.Key, App.Tokens.Secret);
var TokenRequest = new RestRequest("/iphone/json/users/", Method.GET);
HabraClient.ExecuteAsync(TokenRequest, (response =>
{
try
{
if (response.StatusCode == HttpStatusCode.OK)
{
When I execute this request I receive correct response with data.
But if I add parameter (uncomment TokenRequest.AddParameter("page_num", 2); ) I receive "Invalid signature". I have tried to send both int and string parameter.
var TokenRequest = new RestRequest("/iphone/json/users/", Method.GET);
TokenRequest.AddParameter("page_num", 2);
HabraClient.ExecuteAsync(TokenRequest, (response =>
{
try
{
if (response.StatusCode == HttpStatusCode.OK)
{
I receive message "Invalid signature". I have tried string parameter too:
TokenRequest.AddParameter("page_num", "2");
API provider told me, that I have a problem with signature base
string http://oauth.net/core/1.0/#sig_base_example
So, how can i view it? Or maybe you can help me to solve all this
problem?
I think you are breaking the request structure... better to check the request over Fiddler, but try to write something like
var TokenRequest = new RestRequest("/iphone/json/users/?page_num=2", Method.GET);
instead of
var TokenRequest = new RestRequest("/iphone/json/users/", Method.GET);
TokenRequest.AddParameter("page_num", 2);
Hope, it would help.