Android Jelly bean 4.2.2 - webview XMLHttpRequest cannot load - android

In my app I'm using WebView. I'm trying to call POST method that cannot proceed my request.I get this error:
XMLHttpRequest cannot load https://*****/support/create_ticket.
Request header field Content-Type is not allowed by
Access-Control-Allow-Headers. at null:1
It's happening only in device with Jelley bean 4.2.2 in all the other OS it's work fine.
Thanks a lot for the help.

Add this to request headers:
Map<String, String> extraHeaders=new HashMap<>();
extraHeaders.put("Access-Control-Allow-Origin","*");
extraHeaders.put("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept");
You might need to add this too:
extraHeaders.put("Access-Control-Allow-Methods","POST");//you add more:"GET, POST, PUT"
--- Updated based on your code, here is the adjustment:
RestAPI.Groups = $resource('groups/:id', {
id: '#id'
}, {
get: {
method: "GET",
KalseferPrivateAPI: true,
interceptor: Interceptors.get
},
join: method: "POST",
KalseferPrivateAPI: true,
interceptor: Interceptors.post,
headers: {
'Access-Control-Allow-Origin:*',
'Access-Control-Allow-Headers:Origin, X-Requested-With, Content-Type, Accept',
'Access-Control-Allow-Methods:POST'
},
url: 'groups/join'
}, addMember: {
method: "POST",
KalseferPrivateAPI: true,
interceptor: Interceptors.post,
headers: {
'Access-Control-Allow-Origin:*',
'Access-Control-Allow-Headers:Origin, X-Requested-With, Content-Type, Accept',
'Access-Control-Allow-Methods:POST'
},
url: 'groups/:id/users/:users',
params: {
id: '#id',
users: '#users'
}
}
});
I hope that may help,'.

Related

flutter - no json is sent in the body of my http post

this is the code.
Future<http.Response> postRequest () async {
var url ='http://10.0.2.2:3000/api/message';
Map data = {
'message': '12345678901234567890'
};
//encode Map to JSON
var body = json.encode(data);
var response = await http.post(url,
headers: { "accept": "application/json", "content-type": "application/json" },
body: body
);
print("${response.statusCode}");
print("${response.body}");
return response;
}
postRequest();
// also tried this: headers: {"content-type":"application/json" },
In my python flask server, the post message is logging, but with empty body into it.
The flutter app is running on Android Virtual Device and the server is still running on http://0:0:0:0:3000/ and it's using request.get_json() in the method.
Using postman, everything works as expected on my server so I see the problem in the app.
postman details:
POST: http://localhost:3000/api/message
headers
KEY | VALUE
Content-Type | application/json
Body raw
{
"message": "opa"
}
also raised here: https://github.com/flutter/flutter/issues/39351
Try passing :
Future<http.Response> postRequest () async {
var url ='http://10.0.2.2:3000/api/message';
Map<String, String> data = { "message": "opa" };
var body = json.encode(data);
var response = await http.post(url,
headers: { "accept": "application/json", "content-type": "application/json" },
body: body
);
print(response.statusCode);
print(response.body);
return response;
}
postRequest().then((response){
print(response.body);
});
not sure if my finding is precious or not for community, but it seems that the URL was the problem. Everything works now, but I added a / in the end of the string in my flask app.
In Postman, I didn't have to do this. So if you have same problem, take care :)
The log from Flask server:
127.0.0.1 - - [30/Aug/2019 17:41:32] "POST /api/message/ HTTP/1.1" 200 -
opa
My Flask url is:
#app.route('/api/message/', methods=['POST'])
def function():

React-native / AWS API Gateway android issue

I am trying to use react-native with aws api gateway. Same code ( pure JS ) works great on ios but on android it fails with 403 error.
var signedRequest={
"headers": {
"Content-Type": "application/json",
"Accept": "application/json",
"x-amz-date": "20170918T134411Z",
"Authorization": "AWS4-HMAC-SHA256 Credential=ASIAIBC7RQ7MFUIRO7QQ/20170918/ap-northeast-1/execute-api/aws4_request, SignedHeaders=accept;content-type;host;x-amz-date, Signature=9fb6d4d4820024097f25aaa70648fxxx7a54a2db1a67d173189693dc073d0a0bac8",
"x-amz-security-token": "AgoGb3JpZ2luEKn////////xxxG1iKJBHjjvZH0DxcSqE889Wb3Mv+8PwMqrRe/O5dFFmP+9bQj+fSwVIUvmBplKkQB62x/xTelGHoCEOPXpBWLjT2OAUaBXOti7UZyfyMNgg56/Z58yxk4o2/37xPLbhXfODaL8kydFV8IaPJjdbJIX+a0kXycPLBnVIBdukUp9cMVD27mWN41u3w0VP5J8YiMPzrDnwKtb0U37naoIaknMBqNBDkMGQyHal/TBJ3wjJvJWVntrJvex0QKD8rDLHjaoiIYjBd+a04m2pKsBQJ9WQl02TTCPgRp0bb1oARF2hz0Xpi45Ba6a6E9SAL07UcRShTwX6rmxi0dZ38mkSbBMjI45Xg8r/VaRZx6/OyCq3u+nq4bgLCOMKqb/80F"
},
"data": "{\"data\":{\"func\":\"checkIfFacebookSignupComplete\",\"data\":{}}}",
"method": "POST",
"url": "https://xxx.execute-api.ap-northeast-1.amazonaws.com/dev/user/user"
}
var apiResponse=await fetch(signedRequest.url, {
method: signedRequest.method,
body: signedRequest.data,
headers: signedRequest.headers,
})
console.log("Got api response : ", apiResponse)
On iOS it receives a http response 200. However, on android it fails with:
"The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.
The Canonical String for this request should have been
'POST
/dev/user/user
accept:application/json
content-type:application/json; charset=utf-8
host:uihw7hnkn7.execute-api.ap-northeast-1.amazonaws.com
x-amz-date:20170918T134411Z
accept;content-type;host;x-amz-date
6b83b80f2875c2425c28b258886ad98603fd802095e35303a3c2a72528374fb5'
The String-to-Sign should have been
'AWS4-HMAC-SHA256
20170918T134411Z
20170918/ap-northeast-1/execute-api/aws4_request
008853cdfba53255257d9169e1a9c05500d01299da9efd4695ac8c66cb31e5e7'
"
I have tried axios as well . and same result. ( ios works fine, android fails ) I am using react-native 0.42.3.
Anyone got any idea what might be the issue?
After digging around a lot it appears the issue is related to as described here: https://github.com/facebook/react-native/issues/14445 . android okHttp library ( inernally used by react-native ) added charset=utf=8 to the request. So the solution is to calculate sig4 value with header like this:
var signedRequest={
"headers": {
"Content-Type": "pplication/json; charset=utf-8",
"Accept": "application/json",
"x-amz-date": "20170918T134411Z",
"Authorization": "Calculated sig4 auth",
"x-amz-security-token": "AgoGb3JpZ2luEKn////////xxxG1iKJBHjjvZH0DxcSqE889Wb3Mv+8PwMqrRe/O5dFFmP+9bQj+fSwVIUvmBplKkQB62x/xTelGHoCEOPXpBWLjT2OAUaBXOti7UZyfyMNgg56/Z58yxk4o2/37xPLbhXfODaL8kydFV8IaPJjdbJIX+a0kXycPLBnVIBdukUp9cMVD27mWN41u3w0VP5J8YiMPzrDnwKtb0U37naoIaknMBqNBDkMGQyHal/TBJ3wjJvJWVntrJvex0QKD8rDLHjaoiIYjBd+a04m2pKsBQJ9WQl02TTCPgRp0bb1oARF2hz0Xpi45Ba6a6E9SAL07UcRShTwX6rmxi0dZ38mkSbBMjI45Xg8r/VaRZx6/OyCq3u+nq4bgLCOMKqb/80F"
},
"data": "{\"data\":{\"func\":\"checkIfFacebookSignupComplete\",\"data\":{}}}",
"method": "POST",
"url": "https://xxx.execute-api.ap-northeast-1.amazonaws.com/dev/user/user"
}
The new AWS Amplify library (https://github.com/aws/aws-amplify) on the official AWS repo has support for automatic signing to API Gateway. This is part of the API module: https://github.com/aws/aws-amplify/blob/master/media/api_guide.md
You would first install the React Native npm module:
npm install aws-amplify-react-native
Then link the project: https://github.com/aws/aws-amplify/blob/master/media/quick_start.md#react-native-development
After that you can configure APIs:
import Amplify, { API } from 'aws-amplify';
Amplify.configure(
Auth: {
identityPoolId: 'XX-XXXX-X:XXXXXXXX-XXXX-1234-abcd-1234567890ab', //REQUIRED - Amazon Cognito Identity Pool ID
region: 'XX-XXXX-X', // REQUIRED - Amazon Cognito Region
userPoolId: 'XX-XXXX-X_abcd1234', //OPTIONAL - Amazon Cognito User Pool ID
userPoolWebClientId: 'XX-XXXX-X_abcd1234', //OPTIONAL - Amazon Cognito Web Client ID
},
API: {
endpoints: [
{
name: "ApiName1",
endpoint: "https://1234567890-abcdefgh.amazonaws.com"
},
{
name: "ApiName2",
endpoint: "https://1234567890-abcdefghijkl.amazonaws.com"
}
]
}
});
Following that your API Gateway requests are signed using the user's credentials:
let apiName = 'MyApiName';
let path = '/path';
let myInit = { // OPTIONAL
headers: {} // OPTIONAL
}
API.get(apiName, path, myInit).then(response => {
// Add your code here
});
I was fighting with the same issue. GET worked on both platforms, but POST only on iOS. Setting Content-Type to "application/json; charset=utf-8" before signing the request with sigV4Client fixed it for me.
const path = 'https://your-aws-endpoint.com';
const method = 'POST';
const queryParams = {};
const body = {};
const headers = {
'Content-Type' = 'application/json; charset=utf-8';
};
const client = sigV4Client.newClient({
accessKey: ACCESS_KEY,
secretKey: SECRET_ACCESS_KEY,
sessionToken: SESSION_TOKEN,
region: REGION,
endpoint: ENDPOINT,
});
const signedRequest = client.signRequest({
method: method,
path: path,
headers: headers,
queryParams: queryParams,
body: body
});
fetch(signedRequest.url, {
method: method,
headers: signedRequest.headers,
body: JSON.stringify(body)
}).then((results) => {
...
});

Unable to post to Restful API through Ajax using android phone

I am developing Android application using PhoneGap. I am trying to execute simple login module, it works fine in web browser. But when it comes to apk, its not working. It is not able to post request to Restful API.
var usr = $('#email_address').val();
var pass = $('#password').val();
if(usr != '' && pass != ''){
alert("Before Calling Method");
$.ajax({
url:APIURL +"api/sample/sample123",
type: "POST",
crossDomain : true,
data: {username:usr,password:pass},
dataType: "json",
success: function(data){ /*Here I am posting some dummy code, I can't show original code*/
var response = eval(data);
alert(response.response);
}
});
When I am executing this on android phone, I am getting only first alert above i.e "Before Calling Method" but it is not showing another alert. I have configured res/xml/cordova.xml as
<access uri="*" subdomains="true"/>
Also I have referred some previous related doubts from StackOverflow. But It didn't helped me. Please help me to, I am waiting for positive response...
try this one
formData = {
username: $('#email_address').val(),
password: $('#password').val()
}
$.ajax({
url: APIURL + "api/sample/sample123",
type: "POST",
crossDomain: true,
contentType: 'application/json',
data: formData,
dataType: "json",
success: function(data) {
alert(data);
}
});

Jquery ignore error and success json code

I trying consume service with phonegap and android.
My service using localhost return the json with chrome:
{
"GetListaMunicipiosResult": [{
"MunicipioID": "1",
"MunicipioNome": "Florianópolis",
"MunicipioUf":"SC"
}, {
"MunicipioID": "2",
"MunicipioNome": "Jaraguá do Sul",
"MunicipioUf": "SC"
}]
}
In my .js file, I call the GET json with the code:
$('#cidades_page').live('pageshow',function(event){
$.ajax("http://10.0.2.2:56976/MunicipiosService.svc/ListaMunicipios",{
beforeSend: function (xhr) {
$.mobile.showPageLoadingMsg();
alert("beforeSend");
},
complete: function () {
// $.mobile.hidePageLoadingMsg();
alert("complete");
},
contentType: "application/json",
dataType: "jsonp",
jsonp: "callback",
type: "GET",
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(xhr.responseText);
//alert(thrownError);
},
success: function (data) {
alert(JSON.stringify(data));
}
});
});
But when page show, only alert alert("beforeSend") fired, and after nothing happens.
I insert the json call in html using $.ajax(.... and open with chrome and its work. I do not know what else to do.
thanks for help
EDIT
I test in windows phone and now i can get error Error:GetListaMunicipios was not called.
My .js:
$.ajax("http://localhost:56976/MunicipiosService.svc/ListaMunicipios?callback=?",{
beforeSend: function (xhr) {
// $.mobile.showPageLoadingMsg();
alert('beforeSend');
},
complete: function () {
// $.mobile.hidePageLoadingMsg();
alert('complete');
},
contentType: 'application/json; charset=utf-8',
dataType: 'jsonp',
crossDomain: true,
jsonp: 'callback',
jsonpCallback:'GetListaMunicipios',
type: 'GET',
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(xhr.responseText);
alert(thrownError);
},
success: function (data) {
alert('success');
}
});
My WCF Service
namespace GuiaService
{
[ServiceContract]
public interface IMunicipiosService
{
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "ListaMunicipios")]
List<ClsListaMunicipios> GetListaMunicipios();
}
}
thanks for help.
You should use done, fail and always.
success, error and complete are deprecated.
Update: as noted in the comments, this isn't true for how you're using it. I now believe the problem is because you're using jsonp as the type instead of json.
jsonp is designed to call a function automatically when loaded, so your server should be adding a function call to the generated code. It's possible that jQuery expects this behaviour and disables its own callbacks, or uses the jsonp mechanism to trigger its own callbacks, but since your server doesn't actually add the function call, nothing happens.

How do I use PhoneGap to call a webservice

I'm trying to develop an application on phonegap on Android.
What I'm trying to do is call a webservice from my application, this will be used for data access.
I found many sheets online on how to do this, and the simplest one I could find that seems straight forward goes like this
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "POST",
url: "http://www.webservicex.net/stockquote.asmx/GetQuote",
data: "{'usd'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Insert the returned HTML into the <div>.
$('#Content').html(msg.d);
}
});
});
However, All I can see is the text I had already put into the div, the div contents do not change. I'm testing on a Galaxy SIII device directly, not on a simulator.
My guess is that nothing seems to happen because you are getting a fail, not a success. try adding an error handler and see what happens.
.fail(function() { alert("error"); })
You are likely having 'cross domain' issues (because you are trying to get ajax from a different domain) and may need to use JSONP instead of JSON for your dataType. For more info about JSONP, see this post or the docs
EDIT:
Here is a fiddle of this code in action.
$(document).ready(function() {
//here is one way using the 'error' handler
$.ajax({
type: "POST",
url: "/failOnPurpose",
data: "{'usd'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
error:function(jqXHR, textStatus) {
alert("error:" + textStatus);
},
success: function(msg) {
// Insert the returned HTML into the <div>.
$('#Content').html(msg.d);
}
});
//here is another way using the 'fail' request handler
$.ajax({
type: "POST",
url: "/failOnPurpose",
data: "{'usd'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Insert the returned HTML into the <div>.
$('#Content').html(msg.d);
}
}).fail(function(jqXHR, textStatus) {
alert( "fail: " + textStatus );
});
});​

Categories

Resources