在HttpConnection.connect()android上获取异常

时间:2013-12-04 10:13:12

标签: android http httpconnection

在httpConn.connect()中获取Excception; (代码的第5行)代码和执行错误如下所示..我试图将android应用程序连接到互联网..我从互联网获取此代码..但是它给出了异常......代码完全给出了bewlow..i已经添加了已经显示的权限     我不知道什么是te erroe

代码..

 public class httpsData extends Activity {

    ImageView img;

  @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String str = DownloadText("http://www.edumobile.org/android/");
        TextView txt = (TextView) findViewById(R.id.text);
        txt.setText(str);        
    }   

    private String DownloadText(String URL)
    { Log.v("Wasim ","11");
        int BUFFER_SIZE = 2000;
        InputStream in = null;
        try {
            in = OpenHttpConnection(URL);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return "";
        }
        InputStreamReader isr = new InputStreamReader(in);
        int charRead;
        String str = "";
        char[] inputBuffer = new char[BUFFER_SIZE];          
        try {
            while ((charRead = isr.read(inputBuffer))>0)
            {                    
                //---convert the chars to a String---
                String readString = String.copyValueOf(inputBuffer, 0, charRead);
                str += readString;
                inputBuffer = new char[BUFFER_SIZE];
            }
            in.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "";
        }    
        return str;        
    }

    private InputStream OpenHttpConnection(String urlString) 
    throws IOException
    {
        InputStream in = null;
        int response = -1;

        URL url = new URL(urlString); 

        URLConnection conn = url.openConnection();     
       if (!(conn instanceof HttpURLConnection))  
        {
            throw new IOException("Not an HTTP connection");
        }

            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();
            response = httpConn.getResponseCode();                 
            if (response == HttpURLConnection.HTTP_OK) {
                in = httpConn.getInputStream();                                 
    }   
             return in;     
    }
}

错误是这些:

    12-04 14:57:34.947: E/AndroidRuntime(5851): FATAL EXCEPTION: main
    12-04 14:57:34.947: E/AndroidRuntime(5851): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.apps.httpsData/com.apps.httpsData.httpsData}: android.os.NetworkOnMainThreadException
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at android.app.ActivityThread.access$600(ActivityThread.java:130)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at android.os.Handler.dispatchMessage(Handler.java:99)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at android.os.Looper.loop(Looper.java:137)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at android.app.ActivityThread.main(ActivityThread.java:4745)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at java.lang.reflect.Method.invokeNative(Native Method)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at java.lang.reflect.Method.invoke(Method.java:511)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at dalvik.system.NativeStart.main(Native Method)
    12-04 14:57:34.947: E/AndroidRuntime(5851): Caused by: android.os.NetworkOnMainThreadException
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at java.net.InetAddress.getAllByName(InetAddress.java:214)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:341)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at libcore.net.http.HttpEngine.connect(HttpEngine.java:310)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at com.apps.httpsData.httpsData.OpenHttpConnection(httpsData.java:97)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at com.apps.httpsData.httpsData.DownloadText(httpsData.java:42)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at com.apps.httpsData.httpsData.onCreate(httpsData.java:30)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at android.app.Activity.performCreate(Activity.java:5008)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
    12-04 14:57:34.947: E/AndroidRuntime(5851):     ... 11 more

3 个答案:

答案 0 :(得分:4)

您无法在主线程上执行HTTP连接请求。

使用Async Task并在doInBackground()方法中执行http请求。

答案 1 :(得分:0)

为此必须使用异步任务。要执行Server类,请在您希望调用HTTP CONNECTION的方法中使用这些代码-----------            服务器downloadFile = new Server();            downloadFile.execute();

class Server extends AsyncTask<String, Integer, String> {

    @Override
    protected String doInBackground(String... arg0) {
        // TODO Auto-generated method stub
        try{
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
             HttpClient httpclient = new DefaultHttpClient();
             //link
             String adad="http://"+iP+"/"+faCility+"/distt.php";
             HttpPost httppost = new HttpPost(adad);

             nameValuePairs.add(new BasicNameValuePair(uSername,pAssword));
             httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));


              response = httpclient.execute(httppost);
              if(response !=null)
              {

                  HttpEntity entityy = response.getEntity();
                     is = entityy.getContent();

              }


             }catch(Exception e){
                 Log.e("log_tag", "Error in http connection"+e.toString());

            }
        //convert response to string
        if(is !=null){
        try{//StringBuilder sb = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);


              System.out.println("66666666666666");
                   //todo your work here with "is"


              sb = new StringBuilder();
               sb.append(reader.readLine() + "\n");

               System.out.println("77777777777");
               String line="0";
               while ((line = reader.readLine()) != null) {
                             sb.append(line + "\n");

               }

               is.close();
                System.out.println("88888888888888");
              System.out.println(sb);
                result=sb.toString();
    System.out.println("---------------------------------"+result+"---------------------");
                System.out.println("9999999999999999999");
                       }catch(Exception e){
                      Log.e("log_tag", "Error converting result "+e.toString());

                }
        }

        return result;
    }
    protected void onPostExecute(String resultt)
    {
    }
    }

答案 2 :(得分:0)

试试这个..

TextView txt;

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

    txt = (TextView) findViewById(R.id.text);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
        new DownloadText("http://www.edumobile.org/android/").executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new String[]{null});
    else
        new DownloadText("http://www.edumobile.org/android/").execute(new String[]{null});

}

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

        // variables passed in:
        String urls;
        //  constructor
        public DownloadText(String urls) {
            this.urls = urls;
        }

        @Override
        protected void onPreExecute() {
            pDialog = ProgressDialog.show(httpsData.this, "Fetching Details..", "Please wait...", true);
        }


        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub


             int BUFFER_SIZE = 2000;
        InputStream in = null;
        try {

        InputStream in = null;
        int response = -1;

        URL url = new URL(urls); 

        URLConnection conn = url.openConnection();     
       if (!(conn instanceof HttpURLConnection))  
        {
            throw new IOException("Not an HTTP connection");
        }

            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();
            response = httpConn.getResponseCode();                 
            if (response == HttpURLConnection.HTTP_OK) {
                in = httpConn.getInputStream();                                 
    } 

        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return "";
        }
        InputStreamReader isr = new InputStreamReader(in);
        int charRead;
        String str = "";
        char[] inputBuffer = new char[BUFFER_SIZE];          
        try {
            while ((charRead = isr.read(inputBuffer))>0)
            {                    
                //---convert the chars to a String---
                String readString = String.copyValueOf(inputBuffer, 0, charRead);
                str += readString;
                inputBuffer = new char[BUFFER_SIZE];
            }
            in.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "";
        } 
        }

        @Override
        protected void onPostExecute(String result) {
            // Now we have your JSONObject, play around with it.
            if (pDialog.isShowing())
                pDialog.dismiss();

            if(!result.equals(""))
                txt.setText(result);
        }

    }