AFNetworking response - web-services

MyHttpClient *sharedHttpClient = [MyHttpClient sharedClient];
[sharedHttpClient getPath:BASERURL_GENERAL_APPEND_PATH parameters:reqParameter success:^(AFHTTPRequestOperation *mOperation , id responseObject){
NSLog(#"%#",responseObject);
}failure:^(AFHTTPRequestOperation *operation , NSError *error){
//code for failure
}];
i got request as success but it returns response data as NSData type ,i need response string.please help ...

You might be looking for NSString's initWithData:encoding found in the docs https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html
Otherwise you may want to check your web services return content-type

Try this inside the success block:
NSString* response = [mOperation responseString];
If this string is nil, there might be an encoding problem. Check the content-type of your web service.

Related

How to do a POST and GET in VBscript?

I am new to VBscript and am looking for some help to do a POST to an API and pass it a JSON string containing id, password and a scope, then get an answer and parse it. Here is the call I need to make:
POST https://integrations.ezyvet.com/call/getAccessToken { "partner_id": "id8888", "client_id": "id12345", "client_secret": "secret12345", "grant_type": "client_credentials", "scope": “read-diagnosticresult,read-diagnosticresultitem, read-diagnosticrequest,write-diagnosticresult,write-diagnosticresultitem" }
Here is my code:
Dim fso, outFile
Set fso = CreateObject("Scripting.FileSystemObject")
Set outFile = fso.CreateTextFile("c:\temp\JSONoutput.txt", True)
set json = CreateObject("Chilkat_9_5_0.JsonObject")
jsonStr = "{""partner_id"": ""id8888"", ""client_id"": ""id12345"", ""client_secret"": ""secret12345"", ""grant_type"": ""client_credentials"", ""scope"": ""read-diagnosticresult,read-diagnosticresultitem, read-diagnosticrequest,write-diagnosticresult,write-diagnosticresultitem""}"
success = json.Load(jsonStr)
If (success <> 1) Then
outFile.WriteLine(json.LastErrorText)
WScript.Quit
End If
set http = CreateObject("Chilkat_9_5_0.Http")
I need to make my POST here and get a response and am not sure how. Please help.
Thanks a million.
Hi and welcome to stack overflow!
You have tagged chilkat in your question, however you haven addressed it anywhere in the body or the tittle of it, so I was not sure if answer pointing this or not, so I will try to make a bit of both.
without chilkat
You can do this in pure vbs by using ajax, the short answer would be
Dim request
Set request = CreateObject("MSXML2.XMLHTTP")
request.open "GET", "http://www.example.com", False '(1)
request.send infoToSend '(2)
'(3)
Here you set eather "POST" or "GET"
infoToSend contains the information data, formatted as "key=value&key2..."
request.responseText here contains the servers answer as text, parse it as json if you need
You can find information here.
with chilkat
If you still want to use chilkat the main documentation of the http object is here, here is everything you need. If you need an example tho here I've found two:
making a request: https://www.example-code.com/vbscript/http_xmlHttpRequestVerbs.asp
sending a json: https://www.example-code.com/vbscript/http_put_json.asp
I wont paste it here because its too long but the core part of your interest is that you is:
set request = CreateObject("Chilkat_9_5_0.HttpRequest") '(1)
request.HttpVerb = "PUT" '(2)
success = request.LoadBodyFromString(xmlStr,"utf-8") '(3)
Set response = http.SynchronousRequest(endpointDomain,endpointPort,endpointSsl,request)' (4)
you have to create a httpRequest
you set here eather get or post
3.you load here your content, it is your json or what you will send but formatted appropiately
here you have response contain a HttpResponse object with the result
documentation on the HttpResponse, and the HttpRequest

swift 3 alamofire - get request gives response serialization failed

I'm using devise on ruby on rails for authentication. Taking it one step at a time, I have disabled the cookie authentication in order to test retrieving results prior to authentication.
If I go to my browser and navigate to the url that Alamofire is visiting, I get results in JSON format like this :
{"id":250,"name":null,"username":"walker","bio":null,"gender":null,"birth_date":null,"profile_image_url":null}
I'm requesting the alamofire request like this:
Alamofire.request(requestPath, method: .get, parameters: [:], encoding: JSONEncoding.default, headers: [:]).responseJSON { (response) in
if (response.result.isFailure) {
completion(false, "")
} else {
if let result = response.result.value {
completion(true, result)
}
}
}
This is all inside of another method which simply provides with a completion handler as you can see inside of the completion handler of the Alamofire request.
I get an error every single time.
The error says:
responseSerializationFailed : ResponseSerializationFailureReason
What am i doing wrong?
This error indicates that your response is not a JSON formatted data(or something wrong with your API Response), try to use something like post man to check your API response and to make sure every thing is ok before requesting with to swift

How To fire POST Request with params and token

I am new to API testing with jayway RestAssured.
my jmeter url : http://ip:8080/servelet?token=toekntext&methodname={jsontext}
above url is POST Request, i need to fire request in jayway RestAsseured.
url = http://ip:8080/servelet
Response r = given().contentType(CONTENT_TYPE).accept(CONTENT_ACCEPT).headers("user-agent", web).queryParam("token", tokentext).queryParam("methodname", jsonttext).expect().statusCode(200).when().post(url);
Is the above code correct to fire POST Request Here i am getting 500 internal server error, plz help me.
Yes that looks right given that it truly are query parameters that JMeter is sending. I suspect that it might not be since it's very unusual in my experience that include JSON (I assume jsontext is JSON) in the request path. Try switching from queryParam to formParam to see if it makes any difference.
Try restructuring your code,
FULL-URL - url/account?token=TOKEN&sync=TRUE, then you can try post request as below
given().
contentType(ContentType.JSON).body(payload).
queryParam("token", "TOKEN").
queryParam("sync", "TRUE").
when().post(url).then().
statusCode(200).extract().response();

Using pre-signed S3 URL using AFNetworking to upload from an iOS app

I am trying to upload an image from my iPhone app to S3 and then store the S3 url back into my rails app. I am not supposed to embed credentials in the iOS app so the approach i'm taking is to:
Step 1. iPhone app sends a request to my rails server to return a pre-signed S3 URL for uploading the image.
Step 2. Rails server uses aws-sdk gem to generate and return a pre-signed URL How to store data in S3 and allow user access in a secure way with rails API / iOS client?
Step 3. iPhone app uses AFNetworking to post the NSData of the image to S3.
I did my best to follow all the directions I found online but it's not working and the result of step 3 returns Error 401 forbidden. Since I am a newbie at this I don't even know what I am doing wrong.
In Step 2, my code looks like this:
def getS3Url
s3 = AWS::S3.new(
:access_key_id => "MY S3 KEY",
:secret_access_key => "MY SECRET ACCESS KEY"
)
object = s3.buckets[params["bucket"]].objects[params["path"]]
#s3url = object.url_for(:write, { :expires => 20.minutes.from_now, :secure => true }).to_s
end
The url returned from step2 looks something like this: https://s3.amazonaws.com/myapp-bucket-name/images/avatar/user1.png?AWSAccessKeyId=[access key id]&Expires=[expiration timestamp]&Signature=[Signature]
And once i get that URL i try to post to it by doing the following:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:[responseObject valueForKey:#"s3url"] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:jpegData name:#"file" fileName:self.filename mimeType:#"image/png"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
In this code I extract the url out from the returned object with [responseObject valueForKey:#"s3url"], and then pass that as the URL to post. But it doesn't work. Here's the log when i run it in XCode:
Error: Error Domain=AFNetworkingErrorDomain Code=-1011 "Request failed: forbidden (403)" UserInfo=0x156daaf0 {NSErrorFailingURLKey=https://s3.amazonaws.com/myapp-bucket-name/images/avatar/user1.png?AWSAccessKeyId=[access key id]&Expires=[expiration timestamp]&Signature=[Signature], NSLocalizedDescription=Request failed: forbidden (403), NSUnderlyingError=0x156aef90 "Request failed: unacceptable content-type: application/xml", AFNetworkingOperationFailingURLResponseErrorKey= { URL: https://s3.amazonaws.com/myapp-bucket-name/images/avatar/user1.png?AWSAccessKeyId=[access key id]&Expires=[expiration timestamp]&Signature=[Signature] } { status code: 403, headers {
Connection = close;
"Content-Type" = "application/xml";
Date = "Mon, 30 Jun 2014 07:21:33 GMT";
Server = AmazonS3;
"Transfer-Encoding" = Identity;
"x-amz-id-2" = "FJwEeOjV1/osJKgKeHO+/OjXVBEbvW09XxNX2kn1UYIuHswU+LKh0mJODRJDNLXm";
"x-amz-request-id" = 46E84D0967B6D4CD;
} }}
At this point I don't even know what I am doing wrong. Maybe I'm not even posting to the correct URL. Maybe I need to do more than just POST. I spent the entire weekend trying to figure this out and failed. Could someone please help? Thanks.
I faced a similar "challenge". I had to upload with AFNetworking 2.0 an image to an S3 bucket with a pre-signed URL from my server. In one of my many try and error attempts of doing it I got the same 403 error, and what happened to me was that I had to put the right headers in the request:
Content-Type with the mime type of the image
x-amz-acl as public-read for my bucket configuration
The Content-Length seemed to be optional and note that I haven't uploaded the image in multipart.
So this is what I ended up doing:
+(void) uploadImage:(UIImage *)image atUrl:(NSString *)url withMimeType:(NSString *)mimeType withSuccess:(void (^)(id responseObject))success failure:(void (^)(NSError *error))failure {
NSData *imageData = UIImageJPEGRepresentation(image, 0.1);
NSURL *requestURL = [NSURL URLWithString:url];
AFHTTPSessionManager *client = [[AFHTTPSessionManager alloc] initWithBaseURL:requestURL];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:#"PUT"];
[request setValue:mimeType forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:imageData];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[imageData length]] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"public-read" forHTTPHeaderField:#"x-amz-acl"];
[request setURL:requestURL];
NSURLSessionDataTask *task = [client dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error == nil) {
if (success) {
success(responseObject);
}
} else {
if (failure) {
failure(error);
}
}
}];
[task resume];
}
where url is the presigned url that I've got from my server. Check the JPEG compression that I have at 0.1 as you might want a different compression. In my case the image quality is not important.
Adding to josebama's answer above,
I didnt need to add "x-amz-acl" header field, but instead I added "x-amz-date" and "authorization" headers. Both these headers were returned, from the an API that handled communication with Amazon service, along with a signed URL. The upload to the URL was only successful when I added the two aforementioned header values.
Simply including the "x-amz-acl" header, in my case, would result in a failure to upload.
Perhaps some server side parameters differ or perhaps some setup parameters for amazon vary, needless to say that a solution that works for me might not work for others so it might be good a idea to look at your backend setup a bit..

REST services - testing PUT methods in the browser

I've developed REST services. I can test the GET methods by the browser, or by a Client Application. But those who have PUT methods I don't know how to consume them by the browser...
For example, I have this method that turns a lamp on, after I insert the userId:
#PUT
#Path("/lampon")
#Produces({"application/json", "text/plain"})
#Consumes("multipart/form-data")
public boolean turnOnLamp(#FormParam("userId") String userId) throws Exception
{
boolean response = new LampManager().turnOnLamp(userId);
return response;
}
In my client application I do this, and it works:
String webPage = "http://localhost:8080/BliveServices/webresources/services.actuators/lampon";
URL urlToRequest = new URL(webPage);
//Authentication
urlConnection = (HttpURLConnection) urlToRequest.openConnection();
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.setRequestMethod("PUT");
urlConnection.setRequestProperty("Authorization", basicAuth);
urlConnection.setRequestProperty("Content-type", "multipart/form-data");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("userId", "2"));
(...)
But how can I send the userId by the browser?
Another thing, I get this message when I build my project:
SEVERE: Resource methods utilizing #FormParam and consuming "multipart/form-data" are no longer supported. See #FormDataParam.
Thanks
If you want to test the REST-Webservice with your Browser you must install an plugin.
If you use Google Chrome you can install REST Console I also use these plugin to test my Webservice.
https://chrome.google.com/webstore/detail/rest-console/cokgbflfommojglbmbpenpphppikmonn
For Firefox install these REST-Client
https://addons.mozilla.org/en-us/firefox/addon/restclient/
REST CLient is also available for Safari
http://restclient.net/
For Opera you can check out the Simple REST-Client
https://addons.opera.com/en/extensions/details/simple-rest-client/
For your second Question
please try as Consumes value 'application/x-www-form-urlencoded'
To issue a put-request from a browser you could use jQuery's jQuery.ajax(). (http://api.jquery.com/jQuery.ajax/)
For example:
$.ajax({
url: "test-url",
type: "PUT",
data: {userid: 1}
})
Would send a put-request to test-url with the specified data.