React-Native (Android) : Request failed with status code 403 - bscscan api testnet - android

Please help me, I'm so stuck on this problem: I'm making an request BSCSCAN-API-TESTNET with Axios on React Native and the request is working correctly only within the iOS, but it is not working with the Android (403 Forbidden response).
My URL request: https://api-testnet.bscscan.com/api?module=account&action=txlist&address=0x400ee0c820144c8bb559ace1ad75e5c13e750334&sort=desc&apikey=P3A263376TPJHKQ5IXUD4VHUNFQKDJB4G5
I updated the apiKey so don't mind it.
My code: (IOS: oke, android: throw error 403)
try {
const url =
'https://api-testnet.bscscan.com/api?module=account&action=txlist&address=0x400ee0c820144c8bb559ace1ad75e5c13e750334&sort=desc&apikey=P3A263376TPJHKQ5IXUD4VHUNFQKDJB4G5';
const response = await axios.get(url);
} catch (error) {
throw error;
}

Setting the user agent helped me solve the 403 issue.
try {
const url =
'https://api-testnet.bscscan.com/api?module=account&action=txlist&address=0x400ee0c820144c8bb559ace1ad75e5c13e750334&sort=desc&apikey=P3A263376TPJHKQ5IXUD4VHUNFQKDJB4G5';
const response = await axios.get(url, {headers: { "User-Agent": "Mozilla/5.0" }});
} catch (error) {
throw error;
}

Related

Ionic get call not working in real android device (no error in console too)

I am on ionic 4. And I am using httpClient package to make the http calls. Nothing is happening when I hit the function. And I am not getting error in console too.
I know there are many answers for the same issue, but none of them worked for me.
I am importing as import { HttpClient, HttpHeaders } from '#angular/common/http';
My http service as below
this.http.get(fullurl)
.map(data => {
this.loading.dismiss();
console.log(data);
if(msg!="" && msg.length >= 0){
this.loading.dismiss();
}
The httpClient.get is an Observable. Which means you have to use like this:
import { HttpClient } from '#angular/common/http';
constructor(private http: HttpClient) { }
this.http.get(fullUrl)
.subscribe((data) => {
// Success handler
}, (error) => {
// Error handler
});

How to resolve React Native Android Axios Network Error?

I was using Axios post request to do an API call. It was working fine with iOS but for Android, it was shown Network Error 400.
When I try encoded URL with encodeURIComponent like the following and API was successful with status 200.
return await axios.post(encodeURIComponent(url),JSON.stringify(data), config)
.then(({ data }) => {
return { success: 1, data };
})
.catch(error => {
console.log('error', error)
return { success: 0, error: error.message };
});
Since, there little details concerning the problem. I will say make sure the Content-Type header is set. It's always necessary on android.

ionic3 error on android when calling GET HTTP

In Ionic3 I installed import { HttpClientModule } from '#angular/common/http'; and in my code I'm trying to call below url :
testHTTP(){
this.httpClient.get("https://api.upcitemdb.com/prod/trial/lookup?upc=5425016921463").subscribe(
data => {
console.log('Data : ', data);
this.lookup = data["items"][0].title;
}, err => {
console.log('Error : ', err);
this.lookup = JSON.stringify(err);
});
}
but every time it fails with :
{"headers":{"normalizedNames":{},"lazyUpdate":null,"headers":{}},"status":0,"statusText":"Unknown Error","url":null,"ok":false,"name":"HttpErrorResponse","message":"Http failure response for (unknown url): 0 Unknown Error","error":{"isTrusted":true}}
When I click on the button calling testHTTP on Chrome, I get a CORS error with this object (but I can deactivate CORS and get the real response).
How do you setup ionic http for the get to work please ?
You should use a XMLHttpRequest. And dont forget the Headers.
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.upcitemdb.com/prod/trial/lookup?upc=5425016921463", true);
//Really important to set this header
xhr.setRequestHeader("Access-Control-Allow-Origin","http://localhost:8100");
xhr.onreadystatechange = function() {
if(xhr.readyState == xhr.DONE) {
let ResponseFromRequest = xhr.response //Response from your request
}
}
xhr.send(null);

Network request failed React native fetch (Android)

I have a case when fetching SSL API I get the request fetched successfully on IOS
But on android I have an exception as following
TypeError: Network request failed
at XMLHttpRequest.xhr.onerror (index.android.bundle:12910)
at XMLHttpRequest.dispatchEvent (index.android.bundle:13813)
at XMLHttpRequest.setReadyState (index.android.bundle:15406)
at XMLHttpRequest.__didCompleteResponse (index.android.bundle:15262)
at index.android.bundle:15357
at RCTDeviceEventEmitter.emit (index.android.bundle:3851)
at MessageQueue.__callFunction (index.android.bundle:2090)
at index.android.bundle:1948
at MessageQueue.__guard (index.android.bundle:2062)
at MessageQueue.callFunctionReturnFlushedQueue
(index.android.bundle:1947)
Any way to solve this issue?
Only SSL fetch on android fail. If i fetched HTTP API it works
Edit #1
React-native version:0.44.3
Android emulator version: 7.0
Tested devices: Samsung galaxy j7 prime(Real device) and pixel 2 XL (emulator)
Edit #2
this the code
try {
let url = "https://URL_HERE";
console.log(url);
let bodyData = {
user: {
email: user.email//...etc
}
};
let response = await fetch(url, {
headers: {
'Content-Type': 'application/json'
},
method: 'post',
body: JSON.stringify(bodyData)
});
res.code = response.status;
if (res.code === 200) {
let responseJson = await response.json();
}
} catch (error) {
console.error(error);
}
TIA

Angular2 custom request

I am using a custom HTTP request class for adding a Authorization Header to all of my requests, this works fine on almost every android device. Wired thing now is that I got some customer complaints that they are getting the 'No internet connection' error although they have a working network connection (other apps work and the errors are transmitted to the Sentry servers also).
As I am using Sentry error tracking I found out that these customers are all getting the error because the timeout error is thrown after 10 seconds for the first request at app start.
I guessed that something has to be wrong with this request so I built an alpha version for a limited number of users to track down the error (I send the options of every request to Sentry), but the requests look fine.
Next guess was that something is wrong with cordova-plugin-nativestorage on these devices but as I am catching them it should at lease return an empty token. No clue how to fix it right now. Any advice is appreciated!
export class CustomRequest {
apiToken: string = '';
constructor(private http: Http) { }
protected request(options: any): Observable<any> {
// If Native Storage doens't find a token, return an empty
let errorNativeStorage$ = function (): Observable<any> {
return Observable.of({ Token: '' });
};
// Get Token form Native Storage
let token$ = Observable.fromPromise(NativeStorage.getItem('JWT'))
.catch(errorNativeStorage$);
// Handle request errors
let genericError$ = function (error: Response | any): Observable<any> {
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
Raven.captureException(error, { extra: { errorMsg: errMsg } });
return Observable.of({
Errors: { General: 'No internet connection.' }
});
};
// the request
let request$ = (options) => {
return this.http.request(new Request(options))
.retryWhen(error => error.delay(1000))
.timeout(10000, new Error('timeout'))
.map((res: Response) => res.json())
.catch(genericError$);
};
// get the token and build request
return token$
.map(jwt => {
if (options.body) {
if (typeof options.body !== 'string') {
options.body = JSON.stringify(options.body);
}
options.body = options.body.replace(/ /g, '').replace(/\r?\n|\r/g, '');
}
options.headers = new Headers({
'Content-Type': 'application/x-www-form-urlencoded, application/json'
});
if (jwt.Token) {
options.headers.append('Authorization', `Bearer ${jwt.Token}`);
}
Raven.captureMessage('request options', { level: 'info', environment: 'live', extra: options });
return options;
})
.switchMap(options => request$(options));
}
}
I am using:
Ionic 2.0.0-beta.11
Angular 2.0.0-rc.4
Most recent version of NativeStorage plugin from github
Devices with the error (only two examples, there are more):
Samsung SM-N910F (Webview: Chrome Mobile 53.0.2785, Android 6.0.1)
Samsung SM-G800F (Webview: Chrome Mobile 53.0.2785, Android 5.1.1)
If somebody's interested: The root cause was that people that upgraded Android somehow lost the chrome webview app and Angular was not working without one (of course). I solved it by packaging the crosswalk-webview in my app!

Categories

Resources