Android HttpUrl连接 Url 在模拟器上不工作

Android HttpUrlConnection Url doesn't work on emulator

我正在尝试从 url http://digitalcollections.tcd.ie/home/getMeta.php?pid=MS4418_021 中获取 json 对象作为字符串。它不起作用我在 downloadUrl 函数后收到错误。

java.io.IOException: unexpected end of stream on Connection{digitalcollections.tcd.ie:80, proxy=DIRECT@ hostAddress=134.226.115.12 cipherSuite=none protocol=http/1.1} (recycle count=0)

尽管它确实适用于此 androidhive url http://api.androidhive.info/volley/person_object.json。 我是 httpconnection 的新手,下面是我的下载 url 功能。错误似乎显示在这一行 HttpURLConnection conn = (HttpURLConnection) url.openConnection();在该行之后的调试器中 conn.getInputStream() 显示 IO 异常和原因 java.io.EOFException: \n not found: size=0 content=...

 // Given a string representation of a URL, sets up a connection and gets
 // an input stream.
 private InputStream downloadUrl(String urlString) throws IOException {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(20000 /* milliseconds */);
        conn.setConnectTimeout(30000 /* milliseconds */);
        conn.setRequestMethod("GET");
        //conn.setDoInput(true);        
        // Starts the query
        conn.connect();
        InputStream stream = conn.getInputStream();
        return stream;
    }

其他功能。

 // Uses AsyncTask to create a task away from the main UI thread. This task takes a
    // URL string and uses it to create an HttpUrlConnection. Once the connection
    // has been established, the AsyncTask downloads the contents of the webpage as
    // an InputStream. Finally, the InputStream is converted into a string, which is
    // displayed in the UI by the AsyncTask's onPostExecute method.
    private class DownloadXMLTask extends AsyncTask<String, Void, List<Entry>> {
        private String urlFront = "";
        @Override
        protected List<Entry> doInBackground(String... urls) {
            // params comes from the execute() call: params[0] is the url.
            try {
                    return loadJsonFromNetwork(urls[0]);
                } catch (IOException e) {
                    Log.d(TAG, "Unable to retrieve web page. URL may be invalid.");
                    return null;
                } catch (JSONException e) {
                    Log.d(TAG, "XMLPULLPARSER ERROR IN download json task function");
                    return null;
                }
            }

        }
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(List<Entry> result) {
            //post execution stuff
        }
    }

正在加载 json 和解析器,解析器可能无法正常工作尚未测试。

 private List<Entry> loadJsonFromNetwork(String urlString) throws IOException, JSONException {
        InputStream stream = null;
        int len = 20000; //max amount of characters to display in string
        List<Entry> entries = new ArrayList<Entry>();

        try {
            stream = downloadUrl(urlString);  //IOException
            String jsonStr = readit(stream,len);
            if(jsonStr.equals(null)){
                Log.d(TAG, "ERROR json string returned null");
                return entries;
            }
            JSONObject jsonObj = new JSONObject(jsonStr);

            //Not sure if the json parser works yet haven't got that far 
            // Getting JSON Array node
            identifier = jsonObj.getJSONArray("identifier");

            // looping through All Contacts
            for (int i = 0; i < identifier.length(); i++) {
                JSONObject c = identifier.getJSONObject(i);

                String id = c.getString("type");
                if(id.equals("DRIS_FOLDER")) {
                    String folder = c.getString("$");
                    entries.add(new Entry(null,null,null,folder));
                }
            }

            // Makes sure that the InputStream is closed after the app is
            // finished using it.
          //This is where IOexception is called and stream is null
        } catch (IOException e) {
            Log.d(TAG, "Unable to retrieve json web page. URL may be invalid."+ e.toString());
            return entries;
        }
        finally {
            if (stream != null) {
                stream.close();
            }
        }
        return entries;
    }

我在 Nexus_5_API_23 模拟器上 运行 这个。

提前致谢。

更新:

不适用于 Nexus_5_API_23 模拟器??虽然它适用于三星 GT-ST7500 外部 phone。希望它适用于模拟器。

我刚刚在我的设备上尝试 URL 并且没有收到任何错误。这是我使用的代码。

返回 UI 线程的接口

public interface AsyncResponse<T> {
    void onResponse(T response);
}

return 是一个字符串的通用 AsyncTask - 随意修改它以解析您的 JSON 和 return 列表。

public class WebDownloadTask extends AsyncTask<String, Void, String> {

    private AsyncResponse<String> callback;

    public void setCallback(AsyncResponse<String> callback) {
        this.callback = callback;
    }

    @Override
    protected String doInBackground(String... params) {
        String url = params[0];
        return readFromUrl(url);
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        if (callback != null) {
            callback.onResponse(s);
        } else {
            Log.w(WebDownloadTask.class.getSimpleName(), "The response was ignored");
        }
    }

    private String streamToString(InputStream is) throws IOException {

        StringBuilder sb = new StringBuilder();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        while ((line = rd.readLine()) != null) {
            sb.append(line);
        }
        return sb.toString();
    }

    private String readFromUrl(String myWebpage) {

        String response = null;
        HttpURLConnection urlConnection = null;

        try {
            URL url = new URL(myWebpage);

            urlConnection = (HttpURLConnection) url.openConnection();

            InputStream inputStream = urlConnection.getInputStream();
            if (inputStream != null) {
                response = streamToString(inputStream);
                inputStream.close();
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }

        return response;
    }
}

我的 Activity 部分调用 AsyncTask。

String url = "http://digitalcollections.tcd.ie/home/getMeta.php?pid=MS4418_021";

WebDownloadTask task = new WebDownloadTask();
task.setCallback(new AsyncResponse<String>() {
    @Override
    public void onResponse(String response) {
        Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show();
    }
});
task.execute(url);

问题出在我的 antivirus/firewall 我的电脑上。它阻止了我的连接,这就是它在外部 phone 而不是模拟器上工作的原因。我禁用了我的 antivirus/firewall 并且它起作用了。这里有一个网络限制列表 http://developer.android.com/tools/devices/emulator.html#networkinglimitations

确保使用 https 而不是 http 以避免在 Android 模拟器上出现此类错误。

private static final String BASE_URL = "https://content.guardianapis.com/search?";