简体   繁体   中英

sending a http url request

i have been trying to copy the HttpURLConnection snippet from Android developer page into my project just to see if i can make an internet connection and every time i run the function my app closes. i am not sure why the application is failing and any help would be appreciated. this code is being placed inside public class main extends Activity

main.java:

public void showHelp() throws IOException {
        URL url = new URL("http://www.android.com/");
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        try{
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());
            //readStream(in);
        } finally{
            urlConnection.disconnect();
        }
    }

i commented out readStream because i thought the conversion might have been the problem but thats not the case. the function is:

private String readStream(InputStream is) {
        try {
          ByteArrayOutputStream bo = new ByteArrayOutputStream();
          int i = is.read();
          while(i != -1) {
            bo.write(i);
            i = is.read();
          }
          return bo.toString();
        } catch (IOException e) {
          return "";
        }
    }

if posting log cat result helps please let me know. also i am fairly new at android programming and the first function is being called when a menu option is clicked but i didn't think that was relevant. also

<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

are included in the android manifest xml

logcat error:

02-04 21:27:14.468: W/dalvikvm(16978): threadid=1: thread exiting with uncaught exception (group=0x4208d2a0)
02-04 21:27:14.492: E/AndroidRuntime(16978): FATAL EXCEPTION: main
02-04 21:27:14.492: E/AndroidRuntime(16978): android.os.NetworkOnMainThreadException
02-04 21:27:14.492: E/AndroidRuntime(16978):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1118)
02-04 21:27:14.492: E/AndroidRuntime(16978):    at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
02-04 21:27:14.492: E/AndroidRuntime(16978):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
02-04 21:27:14.492: E/AndroidRuntime(16978):    at java.net.InetAddress.getAllByName(InetAddress.java:214)
02-04 21:27:14.492: E/AndroidRuntime(16978):    at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
02-04 21:27:14.492: E/AndroidRuntime(16978):    at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
02-04 21:27:14.492: E/AndroidRuntime(16978):    at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
02-04 21:27:14.492: E/AndroidRuntime(16978):    at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
02-04 21:27:14.492: E/AndroidRuntime(16978):    at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
02-04 21:27:14.492: E/AndroidRuntime(16978):    at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315)
02-04 21:27:14.492: E/AndroidRuntime(16978):    at libcore.net.http.HttpEngine.connect(HttpEngine.java:310)
02-04 21:27:14.492: E/AndroidRuntime(16978):    at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289)
02-04 21:27:14.492: E/AndroidRuntime(16978):    at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239)
02-04 21:27:14.492: E/AndroidRuntime(16978):    at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:273)
02-04 21:27:14.492: E/AndroidRuntime(16978):    at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:168)
02-04 21:27:14.492: E/AndroidRuntime(16978):    at com.MeadowEast.audiotest.MainActivity.showHelp(MainActivity.java:369)
02-04 21:27:14.492: E/AndroidRuntime(16978):    at com.MeadowEast.audiotest.MainActivity.onOptionsItemSelected(MainActivity.java:97)
02-04 21:27:14.492: E/AndroidRuntime(16978):    at android.app.Activity.onMenuItemSelected(Activity.java:2625)
02-04 21:27:14.492: E/AndroidRuntime(16978):    at com.android.internal.policy.impl.PhoneWindow.onMenuItemSelected(PhoneWindow.java:1061)
02-04 21:27:14.492: E/AndroidRuntime(16978):    at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:735)
02-04 21:27:14.492: E/AndroidRuntime(16978):    at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:149)
02-04 21:27:14.492: E/AndroidRuntime(16978):    at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:874)
02-04 21:27:14.492: E/AndroidRuntime(16978):    at com.android.internal.view.menu.ListMenuPresenter.onItemClick(ListMenuPresenter.java:179)
02-04 21:27:14.492: E/AndroidRuntime(16978):    at android.widget.AdapterView.performItemClick(AdapterView.java:298)
02-04 21:27:14.492: E/AndroidRuntime(16978):    at android.widget.AbsListView.performItemClick(AbsListView.java:1280)
02-04 21:27:14.492: E/AndroidRuntime(16978):    at android.widget.AbsListView$PerformClick.run(AbsListView.java:3083)
02-04 21:27:14.492: E/AndroidRuntime(16978):    at android.widget.AbsListView$1.run(AbsListView.java:3983)
02-04 21:27:14.492: E/AndroidRuntime(16978):    at android.os.Handler.handleCallback(Handler.java:615)
02-04 21:27:14.492: E/AndroidRuntime(16978):    at android.os.Handler.dispatchMessage(Handler.java:92)
02-04 21:27:14.492: E/AndroidRuntime(16978):    at android.os.Looper.loop(Looper.java:137)
02-04 21:27:14.492: E/AndroidRuntime(16978):    at android.app.ActivityThread.main(ActivityThread.java:4949)
02-04 21:27:14.492: E/AndroidRuntime(16978):    at java.lang.reflect.Method.invokeNative(Native Method)
02-04 21:27:14.492: E/AndroidRuntime(16978):    at java.lang.reflect.Method.invoke(Method.java:511)
02-04 21:27:14.492: E/AndroidRuntime(16978):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1043)
02-04 21:27:14.492: E/AndroidRuntime(16978):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:810)
02-04 21:27:14.492: E/AndroidRuntime(16978):    at dalvik.system.NativeStart.main(Native Method)

new AsyncTask code:

private abstract class myTask extends AsyncTask<String,Void,Void>{
        protected void doInBackground(String addressName) throws IOException {
            URL url = new URL(addressName);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            try{
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                //readStream(in);
            } finally{
                urlConnection.disconnect();
            }
         }

         protected void onProgressUpdate() {
             //do nothing
         }

         protected void onPostExecute() {
             //toast me
         }
    }

being called from:

 public void showHelp(){
        new myTask().execute("http://www.android.com/");
    }

i can't load to android device i get the problem: Cannot instantiate the Type main.mytask

One reason I can think of is that you are placing network communication on the main thread. You are not allowed to do so. You can use AsyncTask

http://developer.android.com/reference/android/os/AsyncTask.html 

For testing you can add the following in your Main Activity but it is consider bad practice.

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy); 

您应该在不同的线程中进行网络操作

Look your logcat, your problem is NetworkOnMainThreadException so that put your urlconnection into others thread

new Thread(new Runnable() {

    @Override
    public void run() {
        // TODO Auto-generated method stub
        showHelp();
    }
}).start();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM