简体   繁体   中英

Why the same http request works in browser and fails when sent from my Android app?

I'm trying to fetch jSON data from Directus Api and requests are working fine when made from the browser. However, when I send the very same requests from my android app (identical URLs, with 'Authorization' header or with parameters) - the requests fail with java.io.FileNotFoundException and response code 405.

The URL with parameters: WORKS IN BROWSER

http://example.com/dev/public/_/items/cities/1?access_token=my_test_token

The same request with parameters: FAILS IN ADNROID

Uri.Builder builder = new Uri.Builder();
builder.appendQueryParameter("access_token","my_test_token");
//..
URL url = new URL(serverURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.addRequestProperty("Content-Type", "application/json; UTF-8");
conn.addRequestProperty("Accept","application/json; charset=utf-8");
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();

The URL without parameters, sent with header 'Authorization: Bearer my_test_token': WORKS IN BROWSER

http://example.com/dev/public/_/items/cities/1

The same request with 'Authorization: Bearer my_test_token' header: FAILS IN ANDROID

URL url = new URL(serverURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.addRequestProperty("Authorization", "Bearer " + token);
conn.addRequestProperty("Content-Type", "application/json; UTF-8");
conn.addRequestProperty("Accept","application/json; charset=utf-8");
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();

Non of the above requests (with parameters or with 'Authorization') work in Android. Is there any difference between browser and Android requests? Why the same request fails on Android giving java.io.FileNotFoundException but works in the browser? Can anyone help? Thanks.

我发现我正在使用POST并尝试在允许的方法为GET时发送输出流,因此服务器返回405'methodNotAllowed'。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM