Android 应用程序停止工作 - servlets 和 Httpget

标签 android tomcat servlets

我有一个问题。我开始使用 servlet 和 Android 进行冒险,我设计了一个简单的 servlet,它写着“Hello world”。现在我想在我的 Android 应用程序中收到这条消息。我的代码:

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


}

我的小服务程序:

@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();

为什么?

最佳答案

如果您使用的是 API level >= 9,则无需使用 AsyncTask 从 Ui Thread 发出网络请求,只需添加 StrictMode.ThreadPolicy在 Activity onCreate 方法中为:

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

StrictMode.setThreadPolicy(policy); 

关于Android 应用程序停止工作 - servlets 和 Httpget,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14085981/

相关文章:

java - 使用 Parse.com 从数据库获取数据以显示在 ListView 中

运行套接字时android无法关闭对话框

java - 无法获取过滤器 java 中包含 # 符号的整个 url

java - 从 InputStream 或 Byte 数组构造 DataSource

android - 如何实现模拟位置?

Android:如何创建 TextInputLayout 的自定义 UI

java - 每次服务器关闭时连接都会关闭。已添加超时 10000000。

Tomcat 6 和 DNS 查找

java - Hibernate:非法尝试将代理与两个打开的 session 相关联

jquery - 将字符串从servlet传输到jsp页面而不刷新