[英]how to pass the parameters to the urlconnection in java/android?
[英]URLConnection 404 only on Android not on simple Java
我正在努力在外部托管的服務器上獲取JSON。 我編寫了2個單獨的JUnit測試,以在Android環境中測試1個網絡請求,而其中一個僅運行標准PC JUnit(不在android上運行)。
當我使用非基於Android的JUnit(簡單的Java程序)測試時,URLConnection可以正常工作,並且我從urlConnection和JSON接收到響應代碼200。 但是,當我在Android設備上運行相同的靜態函數時,收到的響應代碼為404(找不到文件或位置)。 網址本身已編碼,不包含任何非ASCII字符。
為了不向主機服務器發送垃圾郵件,我將URL替換為http://example.com/JSONLink我嘗試過的方法:1.原始實現:
URL url = new URL("http://example.com/JSONLink");
System.out.println(url);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
int problem = urlConnection.getResponseCode();
urlConnection.connect();
System.out.println("The error code is " + problem);
InputStream inputStream = urlConnection.getInputStream();
此時,urlConnection會引發“文件未找到”錯誤。 我也嘗試過切換
urlConnection.getInputStream();
至
urlConnection.getErrorStream();
錯誤流為我提供了一個HTML文件,該文件指出服務器無法找到該文件。
2.確保Android Manifest包含Internet用戶許可
<uses-permission android:name="android.permission.INTERNET" />
嘗試不推薦使用的Apache HTTPDefaultClient方法,例如:
DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet("http://example.com/JSONLink"); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); InputStream inputStream = httpEntity.getContent();
這些嘗試中的每一項都導致404錯誤。 雖然我相信我了解404錯誤的含義,但我不明白為什么我給它提供一個可以由任何瀏覽器訪問的有效URL(包括在手機/仿真器上使用Chrome)時得到它的原因。
如果此問題是在服務器端,是否有一種方法可以模仿瀏覽器來獲取json?
提前致謝
在這種情況下,始終建議的第一步是對服務器進行交叉檢查。 這是你的問題
如果此問題是在服務器端,是否有一種方法可以模仿瀏覽器來獲取json?
是。 您可以嘗試使用這些chrome插件中的任何一個來測試您的服務器是否從瀏覽器中獲得了預期的響應。
1)高級REST客戶端
https://chrome.google.com/webstore/detail/advanced-rest-client/hgmloofddffdnphfgcellkdfbfbjeloo
2)郵遞員
https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.