2013-12-04 2 views
1

Получение Исключения в httpConn.connect(); (пятая последняя строка кода) Коды и ошибки Exeption приведены ниже. Я пытаюсь подключить приложение Android к интернету. Я получил этот код из Интернета .. но он дает исключение .. Код полностью задан bewlow..i добавили разрешение проявлять уже я не знаю, что это те erroeПолучение исключения в HttpConnection.connect() android

код ..

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 

ответ

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); 
     } 

    } 
+0

Thankx .. я редактировал часть кода для Android 2.3.3 и он сработал. txt = (TextView) findViewById (R.id.text); // if (Build.VERSION.SDK_INT> = Build.VERSION_CODES.HONEYCOMB) // новый DownloadText ("http://www.edumobile.org/android/") .executeOnExecutor (AsyncTask.THREAD_POOL_EXECUTOR, новый String [] {ноль}); // else новый DownloadText ("http://www.edumobile.org/android/") .execute (новый String [] {null}); в этом решении i coddnt «.HONEYCOMB» и «.THREAD_POOL_EXECUTOR» .. на Android 2.3.3..может ли это объяснить? – Shigri

+0

@ user2326962 несколько раз больше, чем ** HONEYCOMB ** api не являются «выполненными», поэтому мы используем 'executeOnExecutor', а' THREAD_POOL_EXECUTOR' - это если серийная асинхронная задача не разрешена, поэтому мы используем пул потоков. – Hariharan

4

Вы не можете выполнить HTTP подключения запрос на основной поток.

Используйте Async Task и выполните http-запрос в doInBackground().

0

Для этой цели вам необходимо использовать asynch task. Для выполнения класса сервера используйте этот код в своем методе, из которого вы хотите вызвать HTTP CONNECTION ----------- Сервер скачатьFile = 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) 
    { 
    } 
    } 
+0

Thankx для valuabel ответ .. >> я попробовал первый ответ, и он работал – Shigri

Смежные вопросы