Android httpurlconnection和basicauthentication

时间:2011-10-06 18:42:20

标签: android http android-asynctask basic-authentication httpurlconnection

我有一个非常难以解决的问题。使用的Api是v11,蜂窝3.0 我从一个带有基本身份验证的XML API下载片段中有一个asynctask。即使我使用edittexts等更改了片段内的参数,它仍然可以正常工作。但是当我尝试从片段外部改变自动完成文本视图时,我突然得到“第1行没有元素”第0列异常。我尝试了androidhttpclient,摆弄了systemprop(http.keepalive),并完全缩小了它的方法。

public void setStations(String a, String b){
    AutoCompleteTextView fromET = (AutoCompleteTextView ) getView().findViewById(R.id.from);  
    fromET.setText(a);

    AutoCompleteTextView toET = (AutoCompleteTextView) getView().findViewById(R.id.to);  
    toET.setText(b);
}

当这个方法执行时,它会破坏我的下载任务。如果我手动编辑这些textview,它可以正常工作。

    class LoadDataTask extends AsyncTask<String, Integer, ArrayList<Reisadvies>> {
        private Exception ex;
        private ProgressDialog pd;

        protected void onPreExecute() {
            //loadprogressdialog
        }

        protected ArrayList<Reisadvies> doInBackground(String... params) {
            try{
                ex = null;
                return new APIreader().getRA(params[0], params[1], params[2],params[3],params[4],params[5], params[6]);
            }catch (Exception e){
                cancel(true);
                pd.dismiss();
                ex = e;
                return null;
            }
        }

        protected void onPostExecute(ArrayList<Reisadvies> ra){
            //send list to activity
        }

        protected void onCancelled() {
            super.onCancelled();
            showError(ex);
        }
    }  

};


public ArrayList<Reisadvies> getRA(String fromStation, String toStation, String viaStation, String dateTime, String departure, String hslAllowed, String yearCard) throws APIException{
    try{
        String uri = url(fromStation, toStation, viaStation, dateTime, departure, hslAllowed,yearCard);
        URL url = new URL(uri);
        HttpURLConnection uc = (HttpURLConnection) url.openConnection();
        if (!url.getHost().equals(uc.getURL().getHost())) {
            throw new APIException("HotspotForwadingActive");
        }
        String basicAuth = "Basic " + "username:password"; //base64 encoded
        uc.setRequestProperty ("Authorization", basicAuth);
        uc.connect();
        BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream(), "UTF-8"));
        try{
            return (ArrayList<Reisadvies>) new XMLParser().parseRP(in);
        }finally{
            uc.connect();
        }
    }catch (Exception e){
        e.printStackTrace();
        throw new APIException(e.getMessage());
    }
}

2 个答案:

答案 0 :(得分:1)

我认为doInBackground存在问题:

pd.dismiss();

您只能在UI线程中对UI元素执行操作。这意味着你可以在onPostExecute方法中执行此操作,或者,如果需要,可以使用runOnUiThread方法:

runOnUiThread(new Runnable() {
    public void run() {
        pd.dismiss();
    }
});

我希望这有用......

答案 1 :(得分:0)

你也是对的,但问题不同了。刚刚发现它是urlencoding。应该立刻想出来,但因为它有时会在其中有空间这一事实而被抛弃:)