亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 HttpResponse 響應代碼中使我的 Android 應用程序崩潰

在 HttpResponse 響應代碼中使我的 Android 應用程序崩潰

繁花如伊 2022-06-04 17:37:58
我正在嘗試獲取 HttpReponse 的響應代碼。我更改了獲取響應的方法,但它不起作用。在我使用這個 try & catch 之前:(url 是函數的參數)try {        HttpClient httpclient = new DefaultHttpClient();        HttpPost method = new HttpPost(url);        if (params != null) {            method.setEntity(new UrlEncodedFormEntity(params));        }        HttpResponse response = httpclient .execute(method);        InputStream inputStream = response.getEntity().getContent();        String result = convertInputStreamToString(inputStream);        return result;    }    catch (ClientProtocolException e) {        e.printStackTrace();    }    catch (IOException e) {        e.printStackTrace();    }    return null;}但是這段代碼給了我一個運行時錯誤HttpResponse response = httpclient .execute(method);
查看完整描述

2 回答

?
烙印99

TA貢獻1829條經驗 獲得超13個贊

這就是谷歌所說的。


為避免創建無響應的 UI,請勿在 UI 線程上執行網絡操作。默認情況下,Android 3.0(API 級別 11)及更高版本要求您在主 UI 線程以外的線程上執行網絡操作;如果不這樣做,NetworkOnMainThreadException則會拋出 a。


您需要在單獨的線程中執行您的 HTTP 請求。這可以在一個AsyncTask.


在您的情況下,您需要在下載完成后更新 UI。使用監聽器通知 UI 線程


public interface ResultsListener {

    public void onResultsSucceeded(String result);

}

這是來自 Google 開發人員指南的示例。我對其進行了編輯,并在結果完成后調用了偵聽器。


 private class HttpRequestTask extends AsyncTask<URL, Integer, String> {


      public void setOnResultsListener(ResultsListener listener) {

           this.listener = listener;

      }


      protected String doInBackground(URL... urls) {

         int count = urls.length;

         for (int i = 0; i < count; i++) {

             String httpResult = // Do your HTTP requests here

             // Escape early if cancel() is called

             if (isCancelled()) break;

         }

         return httpResult;

     }


     // use this method if you need to show the progress (eg. in a progress bar in your UI)

     protected void onProgressUpdate(Integer... progress) {

         setProgressPercent(progress[0]);

     }

     // this method is called after the download finished.

     protected void onPostExecute(String result) {

         showDialog("Downloaded " + result);

         listener.onResultsSucceded(result);

     }

 }

new HttpRequestTask().execute(url)現在您可以通過調用Activity來執行任務。您的活動需要實施ResultsListener. 在該onResultsSucceeded方法中,您可以更新您的 UI 元素。


你看,你可以在你的例子中很好地使用 AsyncTask。你只需要重新格式化你的代碼。


查看完整回答
反對 回復 2022-06-04
?
蝴蝶刀刀

TA貢獻1801條經驗 獲得超8個贊

我使用 AsyncTask 但不再工作請檢查我的代碼


public class RegisterActivity extends Activity {


EditText editusername;

EditText editpassword;

String   username;

String   password;



@Override

protected void onCreate(Bundle savedInstanceState) {


    super.onCreate(savedInstanceState);

    setContentView(R.layout.register);

    editusername = (EditText) findViewById(R.id.username_reg);

    editpassword = (EditText) findViewById(R.id.password_reg);


    Button reg_btn = (Button) findViewById(R.id.reg_btn);

    reg_btn.setOnClickListener(new OnClickListener() {


        @Override

        public void onClick(View arg0) {

            username = editusername.getText().toString();

            password = editpassword.getText().toString();

            new RegisterAsyncTask().execute();

        }

    });

}



class RegisterAsyncTask extends AsyncTask<Void, Void, Boolean> {


    private void postData(String username, String password) {


        HttpClient httpclient = new DefaultHttpClient();

        HttpPost httppost = new HttpPost("myurl");


        try {

            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);

            nameValuePairs.add(new BasicNameValuePair("username", username));

            nameValuePairs.add(new BasicNameValuePair("password", password));

            nameValuePairs.add(new BasicNameValuePair("action", "insert"));


            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            HttpResponse response = httpclient.execute(httppost);

        }

        catch (Exception e)

        {

            Log.e("log_tag", "Error:  " + e.toString());

        }

    }



    @Override

    protected Boolean doInBackground(Void... params) {

        postData(username, password);

        return null;

    }

}}


查看完整回答
反對 回復 2022-06-04
  • 2 回答
  • 0 關注
  • 131 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號