I am hitting the REST API server as a client using Swift 3 programming, I have sent request once and a single response. But the problem is once i posted my data's the data's are inserted twice and getting the response based on the second insert value.
For Example: When i posted new mail address, it inserted into Database, and it iterated again and trying to insert again and i get the response as "Email is already registered". I have tried all the methods from my client side programming.
Few have said that the server by itself restarted again after 40 sec, i'm not sure if that is the case how to overcome this problem.
CODE IN SWIFT 3 CLIENT:(iOS)
func getMailAddress(mailID: String) {
let username = "admin"
let password = "admin"
let loginString = String(format: "%#:%#", username, password)
let loginData: NSData = loginString.data(using: String.Encoding.utf8)! as NSData
let base64LoginString = loginData.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
let getUrl = URL(string: "http://localhost/rest/merchantsignup/mailExists/\(mailID)")
var request = URLRequest(url: getUrl!)
request.httpMethod = "GET"
request.setValue(base64LoginString, forHTTPHeaderField: "Authorization")
let urlConnection = NSURLConnection(request: request, delegate: self)
urlConnection?.start()
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if error != nil {
print(error!)
} else {
do {
let myJSON = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments)
print("myJSON:\(myJSON)")
} catch let err as NSError {
print(err)
}
}
}
task.resume()
}
CODE IN JAVA REST WEBSERVICES:
#GET
#Path("/mailExists/{emailId}")
#Produces(MediaType.APPLICATION_JSON)
public RestResMessagesVO mailExists(#PathParam("emailId")String emailId){
System.out.println(emailId);
MerchantRegistrationDAO mcdao = new MerchantRegistrationDAO();
RestResMessagesVO resObj = new RestResMessagesVO();
resObj.setMessage(mcdao.ismcEmailorPhoneExists("emailAddress",emailId.trim()));
return resObj;
}
You are trying to establish a connection with basic authentication, but actual problem here, while your requesting your server it get hitted twice is
1. you established your connection using request so, by that time it hitted the server once.
2. Then you created an object for NSURLConnection, and you started the connection, by that it hits the server second time.
Because of this only you hit your server twice, and get the response based on the second server hit.
Solution: Try this to overcome your Problem:
let username = "admin"
let password = "admin"
let loginString = String(format: "%#:%#", username, password)
let loginData: NSData = loginString.data(using: String.Encoding.utf8)! as NSData
let base64LoginString = loginData.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
let getUrl = URL(string: "Your URL String")
var request = URLRequest(url: getUrl!)
request.httpMethod = "GET"
request.setValue(base64LoginString, forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: request)
{ (data, response, error) in
if error != nil
{
print(error!)
}
else
{
do {
let JSON = try JSONSerialization.jsonObject(with: data!, options: .allowFragments)
print("YOUR RESPONSE: \(JSON)")
}
catch let err as NSError
{
print(err)
}
}
}
task.resume()
probably that's because you are calling
urlConnection?.start()
and
task.resume()
Related
I want to integrate office365 service management API for collecting events from it.I want to use client credential way to use service to service call but i am getting following error,
{
"error":"invalid_client",
"error_description":"AADSTS50048: Subject must match Issuer claim in the client assertion.
\r\nTrace ID: 1ad7acd8-3945-4fe0-a313-07638eb76e42\r\nCorrelation ID: a6c3a3c9-b737-4bfc-894f-3086c3ce8dfa\r\nTimestamp: 2016-06-09 07:20:15Z",
"error_codes":[50048
],
"timestamp":"2016-06-09 07:20:15Z",
"trace_id":"1ad7acd8-3945-4fe0-a313-07638eb76e42",
"correlation_id":"a6c3a3c9-b737-4bfc-894f-3086c3ce8dfa"
}
i use following doc to integration,
For getting client assersion,
https://msdn.microsoft.com/en-us/library/azure/dn645543.aspx I am getting this. But for Access token,
https://msdn.microsoft.com/en-us/library/office/dn707383.aspx I not getting this as a response getting above error.
Somebody help me please :)
How did you get the client_assertion? The link you provide doesn’t describe how to get the ‘client_assertion’. It acquire the token with the app’s id and secret which is doesn’t support for the Office 365 Management API. You can refer the blog to about the ‘client_assertion’.
And here is an C# code sample which use the ADAL to get the access token for the client credentials flow:
string clientId = "{clientId}";
string certThumbprint = "{copy from mmc}";
certThumbprint = certThumbprint.Replace("\u200e", string.Empty).Replace("\u200f", string.Empty).Replace(" ", string.Empty);
string apiResourceId = "https://manage.office.com";
X509Certificate2 cert = null;
X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
string authority = "https://login.windows.net/{yourTentant}";
var authContext = new AuthenticationContext(authority);
try
{
store.Open(OpenFlags.ReadOnly);
cert = store.Certificates.Find(X509FindType.FindByThumbprint, certThumbprint, false)[0];
}
finally
{
store.Close();
}
var certCred = new ClientAssertionCertificate(clientId, cert);
AuthenticationResult result = null;
try
{
result = await authContext.AcquireTokenAsync(apiResourceId, certCred);
}
catch (Exception ex)
{
}
I'm using the SoapUI API as part of an existing java project.
The application should save the request and response XML in an specific report file.
I wonder if it's possible to get those requests and responses via the API.
The method invoking the TestCaseRunner looks like this
protected void checkTestCase(TestCase testCase) {
TestCaseRunner tr = testCase.run(null, false);
for (TestStepResult tcr : tr.getResults()) {
String status = tcr.getStatus();
String time = tcr.getTimeTaken() + "ms";
/* How to get XML messages?
* String request =
* String response =
*/
}
}
Depending on exactly what kind of test steps you have they might be an instance of a MessageExchange. Casting the TestStepResult to a MessageExchange and calling getRequestContent / getResponseContent might do the trick.
String request = ((MessageExchange)tcr).getRequestContent();
String response = ((MessageExchange)tcr).getResponseContent();
I have used the following way to get the response from the API CAll performed:
runner = testRunner.runTestStepByName("Your Test Case name");
// Here we take the response in ms of the API call
timeTaken = runner.response.timeTaken;
// here we get the HTTP response code.
responseCode = runner.getResponseHeaders()."#status#";
// here we get the response content
String response = runner.getResponseContent();
// here we get the API call endpoint -> in case you need to print it out.
String endPoint = runner.getEndpoint();
I want to send the data to person object. How to do it with PostMethod.
def payload ='<person><nationalId>'+1234567+'</nationalId></person>'
def method = new PostMethod(url)
def client = new HttpClient()
payload = payload.trim()
method.addRequestHeader("Content-Type","text/xml")
method.addRequestHeader("Accept","text/xml,application/xml;q=0.9")
Credentials credentials = new UsernamePasswordCredentials('simple', 'simple');
client.getState().setCredentials(new AuthScope(AuthScope.ANY_HOST,8080, AuthScope.ANY_REALM, "digest"),credentials);
method.setRequestEntity(new StringRequestEntity(payload))
def statusCode = client.executeMethod(method)
println "STATUS CODE : ${statusCode}"
def resultsString = method.getResponseBodyAsString()
method.releaseConnection()
println resultsString
I tried above coding. How to set password and username and password digest also. For that i think status code 400 is coming.Please notify where i made mistake
Try to look at REST Client Builder Plugin. See docs and I guess, you'll find more convenient way to send request
New to Play! Framework and web development in general, I'm trying to do a simple REST GET to a web service and just get some straight-forward JSON in response. Typing the URL into a browser, I get a perfect response, with nicely formatted JSON. Calling it via code, it just blows up:
WS.WSRequest wsRequest = WS.url( serviceURL );
wsRequest.timeout( timeoutTime );
wsRequest.setHeader("Accept", "application/json");
wsRequest.headers.put( "Content-type","application/json" );
wsRequest.mimeType = "application/json";
WS.HttpResponse response = wsRequest.get();
String graphServiceResponse = response.getJson().toString();
Everything executes fine, until the last line where it throws an exception and errors out. I know I have what looks like a lot of redundant code; those are my attempts to fix it. Like I said, typing the "serviceURL" into a browser, it works fine.
Anyone know what I'm doing wrong? Thanks in advance!
Okay, solved this. Just omitted all the sets and such, added authentication and it worked perfectly. Weird.
String stringResponse = "";
try {
// execute GET to graph service
WS.WSRequest wsRequest = WS.url( serviceURL ).authenticate( USERNAME, PASSWORD );
WS.HttpResponse response = wsRequest.get();
stringResponse = response.getString();
... more cool stuff ...
Thanks for looking!
I have tried and found this below code working. 10000 is the timeout parameter in ms.
String baseUrl = "your url";
F.Promise<WSResponse> response = ws.url(baseUrl)
.setQueryParameter(param, value)
.get();
return response.get(10000).asJson().toString();
in facebook fql theres this code
https://developers.facebook.com/docs/reference/api/batch/
curl \
-F 'access_token=…' \
-F 'batch=[ \
{"method": "GET", "relative_url": "me"}, \
{"method": "GET", "relative_url": "me/friends?limit=50"} \
]'\
https://graph.facebook.com
it suppose to to be sent with json
but I really dont understand how to do this
any help ?
thanks
You can simple use the BatchFB api its very powerful and easy , you dont have to deal will all of these stuff and it use the fql
for example to get all your friends
Later<ArrayNode> friendsArrayList = this.Batcher.query("SELECT uid FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me())");
for (JsonNode friend : friendsArrayList.get()) {
.......
}
and its batched
I believe your question is how to execute a batch request using Facebook Graph API. For this you have to issue a POST request to
"https://graph.facebook.com"
and the post data to be sent should be
"batch=[{'method': 'GET', 'relative_url': 'me'}, {'method': 'GET', 'relative_url': 'me/friends?limit=50'}]&access_token=#accesstoken"
in your case [#accesstoken must be replaced with your access token value].
This request will return the details of the owner of the access token(normally the current logged in user) and a list of 50 facebook friends(contains id and name fields) of the user along with page headers(can be omitted).
I am not sure whether you meant java or Javascript. Please be specific on it.
I am a C# programmer basically. Will provide you a code to execute the above request in C# here.
WebRequest webRequest = WebRequest.Create("https://graph.facebook.com");
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-UrlEncoded";
byte[] buffer = Encoding.UTF8.GetBytes("batch=[{'method': 'GET', 'relative_url': 'me'}, {'method': 'GET', 'relative_url': 'me/friends?limit=50'}]&access_token=#ACCESSTOKEN");
webRequest.ContentLength = buffer.Length;
using (Stream stream = webRequest.GetRequestStream())
{
stream.Write(buffer, 0, buffer.Length);
using (WebResponse webResponse = webRequest.GetResponse())
{
if (webResponse != null)
{
using (StreamReader streamReader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
{
string data = streamReader.ReadToEnd();
}
}
}
}
Here the variable data will contain the result.
Salah, here is the example i use as reference, i am sorry though i do not remember where i found.
FB.api("/", "POST", {
access_token:"MY_APPLICATION_ACCESS_TOKEN",
batch:[
{
"method":"GET",
"name":"get-photos",
"omit_response_on_success": true,
"relative_url":"MY_ALBUM_ID/photos"
},
{
"method": "GET",
"depends_on":"get-photos",
"relative_url":"{result=get-photos:$.data[0].id}/likes"
}
]
}, function(response) {
if (!response || response.error) {
console.log(response.error_description);
} else {
/* Iterate through each Response */
for(var i=0,l=response.length; i<l; i++) {
/* If we have set 'omit_response_on_success' to true in the Request, the Response value will be null, so continue to the next iteration */
if(response[i] === null) continue;
/* Else we are expecting a Response Body Object in JSON, so decode this */
var responseBody = JSON.parse(response[i].body);
/* If the Response Body includes an Error Object, handle the Error */
if(responseBody.error) {
// do something useful here
console.log(responseBody.error.message);
}
/* Else handle the data Object */
else {
// do something useful here
console.log(responseBody.data);
}
}
}
});