【问题标题】:How to use HttpGet Request in Android?如何在 Android 中使用 HttpGet 请求?
【发布时间】:2014-06-06 13:32:08
【问题描述】:

我正在使用此代码,但它在 try-catch 中捕获了一个错误。哪里出错了?

当我打印错误时,content.setText(ex.getMessage()); 为空。

以下是相关代码:

public class MainActivity extends Activity {

    TextView content;
    EditText fname, email;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

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

        content = (TextView) findViewById(R.id.content);
        Button saveme = (Button) findViewById(R.id.save);
        saveme.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                Toast.makeText(getBaseContext(), "Please wait, connecting to server.", Toast.LENGTH_LONG).show();

                try {
                    String loginValue = URLEncoder.encode("ffa", "UTF-8");
                    String fnameValue = URLEncoder.encode("fdsfdb", "UTF-8");

                    HttpClient Client = new DefaultHttpClient();
                    String URL = "http://mysite/app.php?a=" + loginValue + "&b=" + fnameValue;

                    try {
                        String SetServerString;
                        HttpGet httpget = new HttpGet(URL);
                        ResponseHandler<String> responseHandler = new BasicResponseHandler();
                        SetServerString = Client.execute(httpget, responseHandler);
                        content.setText(SetServerString);
                    } catch (Exception ex) {
                        content.setText(ex.getMessage());
                    }
                } catch (UnsupportedEncodingException ex) {
                    content.setText(ex.getMessage());
                }
            }
        });
    }
}

【问题讨论】:

标签: java android http get


【解决方案1】:

我认为你得到了 NetworkOnMainThreadException。您应该在后台线程上执行网络通信。考虑使用 IntentService 或 AsyncTask。

【讨论】:

    【解决方案2】:

    我和 Nickolai 有同样的看法。

    解决方法:

    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }
    

    仅当您为自己编写代码时才使用上面的代码。


    如果您的应用程序是生产给其他人的,您需要一个更好的方法。

    更好的方法:

    您应该使用句柄来访问 http-request,more info in developer.android.com

    【讨论】:

      【解决方案3】:

      我自己用这个:

      ByteArrayOutputStream out = new ByteArrayOutputStream();
      response.getEntity().writeTo(out);
      out.close();
      String responseString = out.toString();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-11
        • 1970-01-01
        相关资源
        最近更新 更多