Unable to call restful webservice from JS Adapter - ibm-mobilefirst

I wanted to call a RESTful webservice from mobilefirst 8.0 Javascript Adapter, but the thing is when I am calling it from Javascript Adapter its getting failed but when I am calling the same service from Java Adapter its getting executed successfully. Following is the code:
JS Adapter Code (Not Working)
function addStatus(requestData){
var input = {
method : 'put',
returnedContentType : "application/json;charset=UTF-8",
path : "cli/version/addStatus?version=1&status=APPROVED&UCD_SESSION_KEY=1",
headers: {
"Authorization":"Basic " + requestData.authHeader,
"Accept" : "application/json",
"Content-type": "application/json",
"Connection", "keep-alive"
}
};
var response = WL.Server.invokeHttp(input);
return response;
}
In the response, I am getting status code as 302.
Java Adapter Code (Working)
String pageUrl ="https://my.server.url:port/cli/version/addStatus?version=1&status=APPROVED&UCD_SESSION_KEY=1";
String username = "username";
String password = "password";
HttpClient httpClient = new DefaultHttpClient();
HttpPut httpGet = new HttpPut(pageUrl);
String credential = Base64.getEncoder().encodeToString((username+":"+password).getBytes());
httpGet.setHeader("Authorization", "Basic " + credential);
httpGet.setHeader("Accept", "application/json");
httpGet.setHeader("Connection", "keep-alive");
httpGet.setHeader("Content-type", "application/json");
HttpResponse httpResponse = httpClient.execute(httpGet);
I am not getting any error and I am able to see the changes done by this service. AM I missing something in making the input inside my JS Adapter?

Related

xamarin.forms ,Foursqaure api response is not displaying but works in postman and foursqaure site after providing api key ?where im wrong

private async Task GetresultAsync()
{
var client = new HttpClient();
var request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri("https://api.foursquare.com/v3/places/search?ll=15.3494005,75.142583&query=shops&fields=geocodes,categories,name,hours,fsq_id,price,rating,stats,location"),
Headers =
{
{ "Accept", "application/json" },
{ "Authorization", "fsq322aNlTt3+PuRKw5js/ndngtry/XxNV0Q70yzKjDTQn0="
},
},
};
using (var response = await client.SendAsync(request))
{
response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
Debug.WriteLine(body);
}
Please any suggestions? I'm very new to xamarin and I'm getting data in postman but not getting result in xamarin using
RESTCLIENT OR HTTPCLIENT for( foursqaure places api for v3) where am I wrong?

RabbitMQ HTTP API returning 401 (Unauthorized)

Using RabbitMQ localhost and trying to use his API.. when i Call from postman it's work fine.
But i'm trying to use this API inside my app code and I'm getting 401 error:
const test = {
count: 5,
ackmode: 'ack_requeue_true',
encoding: 'auto',
truncate: 50000
}
testPost() {
fetch('http://localhost:15672/api/queues/%2F/QA.MOBILE/get', {
method: 'post',
mode: 'no-cors',
body: JSON.stringify(test),
headers: {Authorization: 'Basic ' + btoa('guest:guest'), Accept: 'application/json', 'Content-Type': 'application/json'}
});
}
POST http://localhost:15672/api/queues/%2F/QA.MOBILE/get net::ERR_ABORTED 401 (Unauthorized)
I'm missing something?
thanks
I just had this problem myself. Even though my issue was not CORS related, I thought I would document the issue here in case future readers have the same problem.
My issue was that I was not correctly base64ing the user credentials. From a browser you can just call any of the RabbitMQ API endpoints like this:
http://somename:somepassword#servername:15672/api/cluster-name
But when calling it programatically, you need to remove the credentials from the url and base 64 them instead.
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("GET"), "http://servername:15672/api/cluster-name"))
{
var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes($"somename:somepassword"));
request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}");
var response = httpClient.SendAsync(request).Result;
if (response.IsSuccessStatusCode == true)
{
string jsonContent = response.Content.ReadAsStringAsync().Result;
}
}
}
The above code is C# but it would be the same process for Java, etc.

Find out Cookie in Flutter

I use Flutter to make a HTTP-Post to a website to login. If I only send the data to login, the response of the HTTP-Post shows, that I`m not logged in. I tried to find out the cookie the Website sends. I did it with the software Postman. If I add the same cookie, I got at Postman, the HTTP-Post with Flutter works and the response shows, that Im logged in. After a while, the value of the cookie switched and the HTTP-Post via Flutter doent work.
How can I get the information about the actual value of the cookie from the website?
The code looks like this:
Future initiate() async {
ByteData bytes = await rootBundle.load('assets/Certificates/test.crt');
SecurityContext clientContext = new SecurityContext()
..setTrustedCertificatesBytes(bytes.buffer.asUint8List());
var client = new HttpClient(context: clientContext);
IOClient ioClient = new IOClient(client);
var form = <String, String>{
'user':'testuser',
'pass':'testpass',
'logintype':'login',
'pid':'128',
'submit':'Anmelden',
'tx_felogin_pi1[noredirect]':'0'
};
print(form);
var ris = await ioClient.get("https://www.test.de/login");
print(ris.headers);
http.Response res = await ioClient.post("https://www.test.de/login",body:form, headers: {
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded", "Cookie": "fe_typo_user=12345"}, encoding: Encoding.getByName("utf-8"));
ioClient.close();
client.close();
print(res.body.length);
return res.body.contains("logout");
}
This is how I get cookie:
static Future<String> login(String username, String password) async {
var url = _session._getUrl('/auth/login');
var map = new Map<String, dynamic>();
map['username'] = username;
map['password'] = password;
final response = await http.post(url, body: map);
var jsonResponse = convert.jsonDecode(response.body);
var cookies = response.headers['set-cookie'];
if (cookies != null) {
var csrf = _session._getCSRF(cookies);
LocalStorage.instance.setString('CSRF', csrf);
print(csrf);
}
return jsonResponse['msg'];
}

Angular 2 Post fail building request

I'm trying to do a simple post calling to my wcf rest service, and the result is a invalidoperation.
Using fiddler I see the request is not correct, but i don'w know why is not using my parameters.
I try JSON.stringify but don't work
private url = 'http://localhost:34244/CitizenService.svc/register';
public customLogin(user: string, pass: string): Observable<string> {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ method: "POST",headers: headers,body: user} );
return this.http.post(this.url, user, options)
.map(this.extractData)
.catch(this.handleError);
}
And this is angular vs postman request
Anybody knows what's happening?
Thanks.

500 error on UrlFetchApp

I am trying to pass data of a product list from Magento API to Google Spreadsheet.
No authentication was required for the Magento API as I was retrieving the data as a Guest. The API is working perfectly with RestClient.
However, 500 error occurred when fetching the REST resource from Googe Apps Script.
Exception: Request failed for
http://mymagentohost/api/rest/products?limit=2
returned code 500. Truncated server response: Service temporary
unavailable (use muteHttpExceptions option to examine full response)
This is my Google Apps Script:
function myscript() {
var url = "http://mymagentohost/api/rest/products?limit=2"
var response = UrlFetchApp.fetch(url);
var out = JSON.parse(response.getContentText());
var doc = SpreadsheetApp.create("Product Info");
var cell = doc.getRange('a1');
var index = 0;
for (var i in out) {
var value = out[i];
cell.offset(index, 0).setValue(i);
cell.offset(index, 1).setValue(value);
index++;
}
Any ideas?
Hey the trick is to add the following headers to your request
var url = "http://mymagentohost/api/rest/products?limit=2"
var params = {
headers: { 'Content-Type': "application/json", 'Accept': "application/json"},
muteHttpExceptions: true,
method: "GET",
contentType: "application/json",
validateHttpsCertificates: false,
};
var response = UrlFetchApp.fetch(url, params);
Believe the key params for Magento not to return 500 "Service temporary unavailable" are the Content-Type and Accept headers but all params mentioned in example are useful, YMMV.