【问题标题】:HttpURLConnection crashes applicationHttpURLConnection 使应用程序崩溃
【发布时间】:2017-11-16 22:59:50
【问题描述】:

我想通过网络服务器接收和发送数据,但代码不起作用 我该怎么做才能让这段代码起作用?

注意 onCreate 里面的这段代码

try {

    URL url = new URL("http://myweb.com/");
    HttpURLConnection   connection = (HttpURLConnection) url.openConnection();
    InputStream Stream = connection.getInputStream();
    InputStreamReader reader = new InputStreamReader(Stream);
    BufferedReader b = new BufferedReader(reader);
    StringBuilder s = new StringBuilder();
    String str ="";

    while ((str = b.readLine())!=null)  {
        s.append(str);

    }
    String data = s.toString();
    TextView myText = (TextView) findViewById(R.id.Text);
    myText.setText(data);
} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

【问题讨论】:

  • does not work详细说明。你有错误吗?没有服务器响应?收到意外响应代码?

标签: android httpurlconnection


【解决方案1】:

确保您在 Android 中的单独线程上执行与网络相关的任务。另外,请检查您是否拥有INTERNET 权限集。

如果你想从另一个线程更新 UI,你必须使用

runOnUiThread (new Runnable () {
    public void run() {
        //update ui in here
    }
}

【讨论】:

  • 已经出错了,但是服务器没有结果拜托,我想在Facebook上和你谈谈
  • 抱歉,我没有 Facebook 帐户。你可以和我在 StackOverflow 上聊天
【解决方案2】:

您的所有代码都在主线程中运行,主线程应始终用于设置 UI 和侦听 UI 事件,例如点击侦听器。

此线程不允许网络调用,因为它们可能需要很长时间。使用android的AsyncTask API,专为在单独的线程中运行代码而设计。

为所有 GET 请求任务创建一个如下所示的类。

public class DownloadTask extends AsyncTask<String, Void, Integer> {

    private String TAG = "InDownloadTask";
    private DownloadCallback callback;
    private String data;

    public DownloadTask(DownloadCallback cb){
        callback = cb;
    }

    @Override
    protected Integer doInBackground(String... params) {
        Integer result = 0;
        HttpURLConnection urlConnection;
        try {
            URL url = new URL(params[0]);
            urlConnection = (HttpURLConnection) url.openConnection();
            int statusCode = urlConnection.getResponseCode();

            if (statusCode == 200) {
                BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = r.readLine()) != null) {
                    response.append(line);
                }
                data = response.toString();
                result = 1;
            } else {
                result = 0;
            }
        } catch (Exception e) {
            Log.d(TAG, e.getLocalizedMessage());
        }
        return result;
    }

    @Override
    protected void onPostExecute(Integer integer) {
        super.onPostExecute(integer);
        callback.onFinishDownload(data, integer);
    }

}

创建一个我们用于上述类的回调接口。

public interface DownloadCallback {
    public void onFinishDownload(String data, Integer result);
}

现在从您的活动 onCreate

String url = "http://myweb.com/";
new DownloadTask(new DownloadCallback() {
    public void onFinishDownload(String data, Integer result) {
        if(result == 1)
            myText.setText(data);
        else 
            myText.setText("Error");
    }
}).execute(url);

如果您有许多与网络相关的操作,请使用网络库(例如 Volley)来处理此问题。

【讨论】:

    猜你喜欢
    • 2015-10-07
    • 1970-01-01
    • 2012-07-12
    • 1970-01-01
    • 1970-01-01
    • 2017-11-10
    • 2012-08-18
    • 2012-02-12
    • 2014-03-18
    相关资源
    最近更新 更多