2012-12-29 55 views
0

我遇到問題。我開始用servlet和Android開始我的冒險,並且我設計了一個寫入「Hello world」的簡單servlet。現在我想在我的Android應用中收到此消息。我的代碼:Android應用停止工作 - servlets和Httpget

public class MyServlet extends Activity implements OnClickListener{ 

Button button; 
TextView outputText; 

public static final String URL = "http://10.0.2.2:8080/ServletExample/HelloServletExample"; 


@Override 
public void onCreate(Bundle savedInstanceState) { 

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

    findViewsById(); 

    button.setOnClickListener(this); 

} 

private void findViewsById() { 
    button = (Button) findViewById(R.id.button); 
    outputText = (TextView) findViewById(R.id.outputTxt); 
} 

public void onClick(View view) { 

    String output = null; 



     HttpClient httpclient = new DefaultHttpClient(); 
     try { 
      HttpResponse response = httpclient.execute(new HttpGet(URL)); 
      HttpEntity httpEntity = response.getEntity(); 
      output = EntityUtils.toString(httpEntity); 
     } catch (ClientProtocolException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 


    //} catch (ClientProtocolException e) { 
     // TODO Auto-generated catch block 
    //} catch (IOException e) { 
     // TODO Auto-generated catch block 
    //} 



    outputText.setText(output); 


} 

我的servlet:

@WebServlet("/HelloServletExample") 
public class HelloServletExample extends HttpServlet { 
private static final long serialVersionUID = 1L; 

/** 
* @see HttpServlet#HttpServlet() 
*/ 
public HelloServletExample() { 
    super(); 
    // TODO Auto-generated constructor stub 
} 

/** 
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 
*/ 
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 

    PrintWriter out = response.getWriter(); 
    out.println("Hello World"); 

} 

} 

我不知道爲什麼,但我的應用程序崩潰。我嘗試了一些註釋,結果發現問題是這條線:

HttpEntity httpEntity = response.getEntity(); 

爲什麼?

+0

如果你對此有何評論'HttpEntity httpEntity = response.getEntity();'線然後它的工作?如果是,那麼在應用程序崩潰後在logcat中搜索「NetworkOnMainThreadException」 –

+0

我確實有這個例外。爲什麼?我的應用是Android 4,我在互聯網上閱讀,我這樣做的方式是檢索數據的正確方法。 – user1928115

+0

噢,我必須使用AsyncTask? – user1928115

回答

0

如果您正在使用API級別> = 9則沒有必要使用AsyncTask從UI線程進行網絡請求只需添加StrictMode.ThreadPolicy在活動onCreate方法爲:

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

StrictMode.setThreadPolicy(policy); 
+0

,則無需使用AsyncTask那麼,使用此10.0.2.2應用程序會掛起...當我將其更改爲本地主機時,它什麼都不會收到。哪裏有問題? 但是,謝謝你,它不會崩潰了! – user1928115

+0

@ user1928115:如果此答案有助於您解決當前問題,請將其標記爲答案。謝謝 –