Making a HTTP-GET Request with Titanium.Network.createHTTPClient() - httpwebrequest

I am working with Titanium Studio and I have to make an HTTP get request to Couchdb. This is my code:
var url ="http://192.168.0.152:5985/hello_world/00a271787f89c0ef2e10e88a0c0001f4";
var json;
var xhr = Ti.Network.createHTTPClient({
onload: function() {
Ti.API.info("Received text: " + this.responseText);
json = JSON.parse(this.responseText);
},
onerror: function(e) {
Ti.API.debug("STATUS: " + this.status);
Ti.API.debug("TEXT: " + this.responseText);
Ti.API.debug("ERROR: " + e.error);
alert('There was an error retrieving the remote data. Try again.');
},
timeout:5000
});
xhr.open("GET", url);
xhr.send();
The operation go in time out..

the code works fine. I tested it with a different URL.
first check the URL in a web browser to see how much it takes to load, then increase the timeout value.
if it works fine try opening the URL in the browser of the simulator, you may find that it's an IP problem

It is an ip problem in couchdb; couchdb server listen in 127.0.0.1.

Related

Axios get : response with 403 error forbidden

I'm trying to use Open API in Vue.js.
When the webpage was created, i just wanna check the fetched data on console log.
This is the error image. enter image description here
And this is Network tab. enter image description here
code
created() {
const request = require("request");
const SERVIECE_KEY =" blah blah"; // secret
let url =
"https://cors-anywhere.herokuapp.com/http://openapi.molit.go.kr:8081/OpenAPI_ToolInstallPackage/service/rest/RTMSOBJSvc/getRTMSDataSvcAptTrade";
// use 'herokuapp' as a proxy server
let queryParams =
"?" +
encodeURIComponent("serviceKey") +
`=${SERVIECE_KEY}`;
queryParams +=
"&" +
encodeURIComponent("LAWD_CD") +
"=" +
encodeURIComponent("11110");
queryParams +=
"&" +
encodeURIComponent("DEAL_YMD") +
"=" +
encodeURIComponent("201512");
request(
{
url: url + queryParams,
method: "GET",
},
function (error, response, body) {
console.log("Status", response.statusCode);
console.log("Headers", JSON.stringify(response.headers));
console.log("Reponse received", body);
}
);
},
Try
The same request works on Postman with encoded service key (no proxy server URL).
it works on a browser as well.
Use decoded and encoded service key both above the code to check if the URL i entered is wrong
I know 403 error(forbidden) is due to the permission to access.
But i really don't know what could be the problem.

VueJS - Localhost API requests not working on Android Chromium

I am running a vue-project on Chromium 72 on Android v4.4.4 and an API is also running on localhost:8225.
So with the click of a button, I am making a post request using Axios to this localhost API in the project.
var axiosConfig = {
method: "post",
url: "http://localhost:8225/info/update",
data: {},
timeout: 3000,
contentType: "application/json",
headers: {
Authorization: "Basic " + btoa(apiUser + ":" + apiPassword),
},
};
return new Promise(function (resolve, reject) {
axios(axiosConfig)
.then(function (response) {
var result = response;
resolve(result);
console.log("Response", response);
})
.catch(function (error) {
console.log("Error", error);
reject(error);
});
});
But the problem is when I click the button it doesn't hit the API method. It gives Error: timeout of 3000ms exceeded and when I removed the timeout and checked the network tab the request remains in a pending state.
I don't think there is a structural error in the code because the same request works from another application running on the device. When the button is clicked the information gets updated.
Also, I tried all the chromium version till v80 same issue exists. So is there any setting that needs to be changed or enabled on Chromium to handle API requests?
UPDATE:
The API gets hit but when I checked the value of the User(username and password) on HttpListenerContext object, it shows null. I have cross-checked multiple times and I believe the request structure is correct. I am not sure if Chromium is putting some restrictions while sending the requests or the problem is with the backend like CORS issue or maybe something else.

How can I read the LtpaToken2 token from my XMLHttpRequest response?

I'm trying to debug another developers code which looks like this:
xhr.open("POST", url, true, this.state.userid, this.state.password);
xhr.withCredentials = true;
xhr.onload = () => {
console.log("here is our packet " + JSON.stringify(xhr));
if (xhr.status === 200) {
var test = xhr.getAllResponseHeaders();
var respoheader = JSON.stringify(xhr.responseHeaders);
var token = respoheader.substring(
respoheader.indexOf("LtpaToken2"),
respoheader.indexOf(
";",
respoheader.indexOf("LtpaToken2")
)
);
console.log("token is parsed ===" + token);
When I run this query from Postman I see two "Set-Cookie" headers added to the response, and one has the content "LtpaToken2=YpMnhu...", which is apparently what I need to grab. But when I run the code above, it does not include this header. I apparently need to grab this token for future calls to another API.
Can someone explain what I'm doing wrong? How can I capture this token, or how am I supposed to connect to another API without this token? As it seems to always be the case with IBM tech, I can find almost ZERO documentation about LtpaTokens.

Unable to connect to adapter

I have following code called when loading the page:
var resourceRequest = new WLResourceRequest(
"adapters/adapter-name/rest/init/" + timeStamp,
WLResourceRequest.GET
);
However it returns error in my console:
GET http://localhost:10080/project-name/adapters/adapter-name/rest/init/0 404
(Not Found)
While this code works:
function wlEnvInit() {
console.log("CONNECTING 1111");
WL.Client.connect({c
onSuccess: function(){
console.log("CONNECTED 2222");
},
onFailure: function(error) {
console.log("ERROR IN CONNECTION");
console.log(error);
}
});
}
How to troubleshoot this?
Make sure the adapter is really deployed by visiting the console
Make sure that your application is pointing to an IP address of the host machine where the MobileFirst Server is deployed to
Make sure your adapter call is correct
Example calling:
Client side:https://github.com/MobileFirst-Platform-Developer-Center/ResourceRequestCordova/blob/release80/www/js/index.js#L54
Server side: https://github.com/MobileFirst-Platform-Developer-Center/Adapters/blob/release80/JavaAdapter/src/main/java/com/sample/adapter/JavaAdapterResource.java#L25

File upload Http client issue Titanium

I am trying to upload a .mp4 file to some server. I am using the HTTP client provided by titanium. when I upload the file, HTTP client is adding some headers in the file due to which the file gets corrupted and cannot be played. When I download the uploaded file and open it in notepad I can see the header which are added to the file.
What should I do so that these headers are not added to the file?
Thanks a lot!
// CODE
var uploadFile = Titanium.Filesystem.getFile(dir, _previewUrl);
var fileUploadUrl = 'Some Url for the server to upload';
var headers = { 'Content-Type' : 'multipart/form-data' };
var content = { 'file' : uploadFile };
var xhr = Titanium.Network.createHTTPClient();
for(var key in _headers) {
xhr.setRequestHeader(key, _headers[key]);
}
xhr.onerror = function(e)
{
Ti.UI.createAlertDialog({title:'Error', message:e.error}).show();
Ti.API.info('IN ERROR ' + e.error);
};
xhr.setTimeout(20000);
xhr.onload = function(e)
{
Ti.UI.createAlertDialog({title:'Success', message:'status code ' + this.status}).show();
Ti.API.info('IN ONLOAD ' + this.status + ' readyState ' + this.readyState);
};
xhr.onsendstream = function(e)
{
ind.value = e.progress ;
Ti.API.info('ONSENDSTREAM - PROGRESS: ' + e.progress);
};
// open the client
xhr.open('POST',fileUploadUrl);
// send the data
xhr.send(content);
// END
try setting the headers after you call xhr.open
// open the client
xhr.open('POST',fileUploadUrl);
for(var key in _headers) {
xhr.setRequestHeader(key, _headers[key]);
}
Do not add { 'Content-Type' : 'multipart/form-data' }; header. This way you should get the file properly without any headers like boundary and file name etc. I could send image, 3gpp file like that successfully But, when I send a video file, my server PHP code $_FILES will be empty array. Even the $_FILES["files"]["error"] have no value. There should some other trick to send video file. (Titanium SDK 3.1.1 & android 4.1.2)
xhr.open("POST", URL);
xhr.send({
files : Titanium.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, sourcefilename)
});
}
Try not sending the raw blob itself. Send base64 encoded string instead.
var uploadFile = Titanium.Filesystem.getFile(dir, _previewUrl);
var base64File = Ti.Utils.base64encode(uploadFile.read()).toString();
And try changing the header to
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(base64File);
That will solve your problem.