android url总是返回空字符串

时间:2015-07-01 08:42:02

标签: android

所以这是我的代码,我已经尝试了基本java上的getContent,它运行正常。但这里根本没有。我加载的网址内容始终为空。我还将权限.INTERNET添加到清单中。我是android的新手

<div id="out"></id>

这是我的清单

@Override
protected void onCreate(Bundle savedInstanceState) {
    String lines="";
    try {
        lines=getContent("http://detik.com");
    }catch (Exception e) {e.printStackTrace();}
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
    alertDialogBuilder.setMessage(lines);

    alertDialogBuilder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface arg0, int arg1) {
            Toast.makeText(MainActivity.this, "You clicked yes button", Toast.LENGTH_LONG).show();
        }
    });

    alertDialogBuilder.setNegativeButton("No",new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            finish();
        }
    });

    AlertDialog alertDialog = alertDialogBuilder.create();
    alertDialog.show();

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public static String getContent(String url) {
    String pageContent="";
    try
    {
        URL pageLink=new URL(url);
        BufferedReader in=new BufferedReader(new InputStreamReader(pageLink.openStream()));

        String line=in.readLine();
        while (line!=null)
        {
            pageContent=pageContent+line;
            line=in.readLine();
        }
        in.close();
    } catch (Exception e) {e.printStackTrace();}
    return "content of "+url+" : "+pageContent;
}

2 个答案:

答案 0 :(得分:1)

请尝试以下功能:

public void getContent(String url) {

        new AsyncTask<Void, Void, String>() {

            @Override
            protected String doInBackground(Void... voids) {

                HttpURLConnection conn = null;

                try {
                    conn = (HttpURLConnection) new URL(url).openConnection();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (conn != null) {
                    conn.setRequestProperty("Accept", "application/json,text/html");
                    conn.setRequestProperty("Content-Type", "application/json");
                    conn.setRequestProperty("Cookie", "");

                    try {
                        InputStream is = conn.getInputStream();
                        BufferedReader br = new BufferedReader(new InputStreamReader(is,
                                "UTF-8"));
                        StringBuffer sb = new StringBuffer();
                        String line;
                        while ((line = br.readLine()) != null) {
                            sb.append(line).append("\n");
                        }
                        br.close();
                        is.close();
                        conn.disconnect();
                        return sb.toString();

                    } catch (SocketException e) {// connection reset
                        Log.d(TAG, "SocketException: " + e);
                        return null;
                    } catch (Exception e) {// connection reset
                        Log.d(TAG, "Exception: " + e);
                        return null;
                    }
                }
                return null;
            }

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

                // You get the result here

            }
        }.execute(null, null, null);
    }

Http连接被认为是耗时的操作,所以你需要把它放到另一个线程而不是UI线程中,所以在我使用AsyncTask的示例中,结果将在onPostExcecute函数中。

答案 1 :(得分:0)

你不能做&#34;互联网工作&#34;在主线程上,你必须像那个例子一样使用AsyncTask。

try {
    BufferedReader br = new BufferedReader(new FileReader("D:\\a.txt"));
    int counter = 0;
    ArrayList<String> list = new ArrayList<String>();
    for (String line; (line = br.readLine()) != null;) {
        counter++;

        if (counter > 51) {
            line = line.trim();
            list.addAll(Arrays.asList(line.split("\\s*,\\s*")));
        }
    }

    String[] array = new String[list.size()];
    array = list.toArray(array);

    for (int i = 0; i < array.length; i++) {
        System.out.println(array[i]);
    }
} catch(Exception e) {
    System.out.println(e);
}

要执行异步任务,单击按钮时,只需写下:

private class AsyncTaskDownloadSomething extends 
        AsyncTask<String[], String, String> {

    DataClassLentABook  mData;





    @Override 
    protected void onPreExecute() { 
        super.onPreExecute(); 
        //Do some prepartations over here, before the task starts to execute 
        //Like freeze the button and/or show a progress bar 


    } 





    @Override 
    protected String doInBackground(String... urls) {
        // Task starts executing. 
        String url = urls[0];

        // Execute HTTP requests here, with one url(urls[0]), 
        // or many urls using the urls table 
        // Save result in myresult 

        return myresult; 

    } 





    protected void onPostExecute(String result) {
               //Do modifications you want after everything is finished 
               //Like re-enable the button, and/or hide a progressbar 
               //And of course do what you want with your result got from http-req 



    } 
}