url.openStream()不能在android上运行

时间:2016-10-28 11:39:14

标签: java android

Java代码应该从facebook graph api下载源代码,但不起作用。代码输出为 <g:select name="user.age" from="${18..65}" value="${age}" noSelection="['':'-Choose your age-']"/> <g:if test="${age==30} "> Hello </g:if> 这是java代码:

htmlCode = ""

AndroidManifest:

package cz.apps;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.*;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    public String htmlCode = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ziskatdata();
    }

    public void ziskatdata(){
        try {
            URL url = new URL("https://graph.facebook.com/v2.8/****/events?access_token=****");
           BufferedInputStream bis = new BufferedInputStream(url.openStream());
           byte[] buffer = new byte[1024];
           StringBuilder sb = new StringBuilder();
           int bytesRead = 0;
           while((bytesRead = bis.read(buffer)) > 0) {
               String text = new String(buffer, 0, bytesRead);
               sb.append(text);
           }
           bis.close();

         htmlCode = sb.toString();
        } catch (Exception e) {
            //Data se nestáhla
        }

        if (htmlCode.equals("")){
            //Nezdařilo se vypsat události
        } else {
            try {
                JSONObject json = new JSONObject(htmlCode);
                JSONArray jarray = json.getJSONArray("data");
                for(int i = 0; i < jarray.length(); i++){
                    JSONObject udalosti = jarray.getJSONObject(i);
                    String popis = udalosti.getString("description");
                    String konec = udalosti.getString("end_time");
                    String zacatek = udalosti.getString("start_time");
                    String jmeno = udalosti.getString("name");

                    JSONObject lokace = udalosti.getJSONObject("place").getJSONObject("location");
                    String mesto = lokace.getString("city");
                    String zeme = lokace.getString("country");
                    String lat = lokace.getString("latitude");
                    String lon = lokace.getString("longitude");
                    final TextView textViewToChange = (TextView) findViewById(R.id.textprovypsani);
                    textViewToChange.setText(mesto);
                }
            } catch (JSONException e) {
                //Něco je špatně
            }
        }
    }
}

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cz.app" > <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> LogCat输出:

catch (Exception e) { Log.e("MYAPP", "exception", e); }

2 个答案:

答案 0 :(得分:1)

您必须在mainUI Thread中使用此代码。所以,

new Thread(new Runnable() {
    public void run() {
        try {
            ziskatdata();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}).start();

并在方法内部使用以下方法更新所有UI视图:

runOnUiThread(new Runnable() {
    public void run() {
        try {
            textViewToChange.setText(mesto);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
});

答案 1 :(得分:0)

错误表明您尝试在应用程序的主线程上进行网络调用,这是不允许的。您需要生成另一个线程来进行网络调用。你可以这样做:

new Thread() {
    @Override
    public void run() {
        // do your work here
    }
}.start();

但是你不能在该线程上做任何与UI相关的事情。您还可以使用类AsyncTask

这样的类
new AsyncTask<Void, Void, String>() {
    @Override
    protected String doInBackground(Void... params) {
        String response = whatEverMethodGetsMeNetworkCallResponse();

        return response;
    }

    @Override
    protected void onPostExecute(String response) {
        super.onPostExecute(response);

        // Do whatever you want to do with the network response
    }
}.execute();

您可以使用帮助程序类来访问Web API,例如我的一个:Network.java

它将处理读取和写入流的所有复杂问题,您可以调用URL,并在需要二进制文件时将响应作为字符串或Stream获取。