Android HttpUrlConnection Url不';不能在模拟器上工作
我试图从这个url获取json对象作为字符串。它不工作,我下载URL函数后出错Android HttpUrlConnection Url不';不能在模拟器上工作,android,json,emulation,ioexception,httpconnection,Android,Json,Emulation,Ioexception,Httpconnection,我试图从这个url获取json对象作为字符串。它不工作,我下载URL函数后出错 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
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。
我不熟悉httpconnection,下面是我的下载url函数。此行HttpURLConnection conn=(HttpURLConnection)url.openConnection()中似乎显示了错误;在调试器中,该行后面的conn.getInputStream()显示IO异常和原因java.IO.EOFException:\n未找到: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
}
}
//使用AsyncTask创建远离主UI线程的任务。这项任务需要一段时间
//URL字符串,并使用它创建HttpUrlConnection。一旦连接
//已建立,AsyncTask将下载网页的内容,如下所示
//输入流。最后,InputStream被转换成一个字符串,它是
//通过AsyncTask的onPostExecute方法在UI中显示。
私有类DownloadXMLTask扩展了AsyncTask{
私有字符串urlFront=“”;
@凌驾
受保护列表doInBackground(字符串…URL){
//params来自execute()调用:params[0]是url。
试一试{
返回loadJsonFromNetwork(URL[0]);
}捕获(IOE异常){
Log.d(标记“无法检索网页。URL可能无效”);
返回null;
}捕获(JSONException e){
d(标记“下载json任务函数中的XMLPULLPARSER错误”);
返回null;
}
}
}
//onPostExecute显示异步任务的结果。
@凌驾
受保护的void onPostExecute(列表结果){
//刑满释放
}
}
加载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;
}
private List loadJsonFromNetwork(字符串urlString)抛出IOException、JSONException{
InputStream=null;
int len=20000;//字符串中显示的最大字符数
列表项=新的ArrayList();
试一试{
stream=downloadUrl(urlString);//IOException
字符串jsonStr=readit(流,len);
if(jsonStr.equals(null)){
d(标记“ERROR json string returned null”);
返回条目;
}
JSONObject jsonObj=新的JSONObject(jsonStr);
//还不确定json解析器是否工作,但还没有达到这一步
//获取JSON数组节点
标识符=jsonObj.getJSONArray(“标识符”);
//通过所有触点循环
对于(int i=0;i
我在Nexus_5_API_23模拟器上运行这个
提前谢谢
更新:
在Nexus_5_API_23模拟器上不工作??尽管它可以在三星GT-ST7500外置手机上使用。希望它能在模拟器上运行。我刚刚在我的设备上尝试了该URL,没有收到任何错误。这是我使用的代码 返回UI线程的接口
public interface AsyncResponse<T> {
void onResponse(T response);
}
公共接口异步响应{
无效反应(T反应);
}
一个返回字符串的通用AsyncTask—可以随意修改它来解析JSON并返回列表
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;
}
}
公共类WebDownloadTask扩展了AsyncTask{
私有异步响应回调;
公共void setCallback(异步响应回调){
this.callback=回调;
}
@凌驾
受保护的字符串doInBackground(字符串…参数){
字符串url=params[0];
返回readFromUrl(url);
}
@凌驾
受保护的void onPostExecute(字符串s){
super.onPostExecute(s);
if(回调!=null){
回调。onResponse;
}否则{
w(WebDownloadTask.class.getSimpleName(),“响应被忽略”);
}
}
私有字符串streamToString(InputStream is)引发IOException{
StringBuilder sb=新的StringBuilder();
BufferedReader rd=新的BufferedReader(新的InputStreamReader(is));
弦线;
而((line=rd.readLine())!=null){
某人附加(行);
}
使某人返回字符串();
}
私有字符串readFromUrl(字符串myWebpage){
字符串响应=null;
HttpURLConnection-urlConnection=null;
试一试{
URL=新URL(我的网页);
urlConnection=(HttpURLConnection)url.openConnection();
InputStream InputStream=urlConnection.getInputStream();
如果(inputStream!=null){
响应=streamToString(inputStream);
inputStream.close();
}
}捕获(IOE异常){
e、 printStackTrace();
}最后{
if(urlConnection!=null){
urlConnection.disconnect();
}
}
返回响应;
}
}
调用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);
stringurl=”http://digitalcollections.tcd.ie/home/getMeta.php?pid=MS4418_021";
WebDownloadTask任务=新建WebDownloa
private static final String BASE_URL = "https://content.guardianapis.com/search?";