我正在处理我的Web服务,同时获得响应 - 如何从服务器端获得响应?

时间:2013-09-04 05:00:10

标签: android web-services post httpclient

我使用post方法调用Web服务并在调用Web服务时出错。

logcat的:

09-04 04:58:56.437: E/AndroidRuntime(803): FATAL EXCEPTION: AsyncTask #1
09-04 04:58:56.437: E/AndroidRuntime(803): java.lang.RuntimeException: An error occure while executing doInBackground()

我正在使用的网络服务是 class AttemptLogin扩展了AsyncTask {

     /**
     * Before starting background thread Show Progress Dialog
     * */
    boolean failure = false;

    @Override
    protected void onPreExecute() {
         String username = user.getText().toString();
         String password = pass.getText().toString();
        super.onPreExecute(); 

        pDialog = new ProgressDialog(Loginpage.this);
        pDialog.setMessage("Attempting login...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();

    }

    @Override
    protected String doInBackground(String... args) {
        // TODO Auto-generated method stub
         // Check for success tag
        String username=args [0];
        String password=args[1];
        int success;

        try {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();


            params.add(new BasicNameValuePair("username", username));
            params.add(new BasicNameValuePair("password", password));

            Log.d("request!", "starting");
            // getting product details by making HTTP request
            JSONObject json = jsonParser.makeHttpRequest(
                   LOGIN_URL, "POST", params);

            // check your log for json response
            Log.d("Login attempt", json.toString());

            // json success tag
            success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                Log.d("Login Successful!", json.toString());
                Intent i = new Intent(Loginpage.this, Propertyapp.class);
                finish();
                startActivity(i);
                return json.getString(TAG_MESSAGE);
            }else{
                Log.d("Login Failure!", json.getString(TAG_MESSAGE));
                return json.getString(TAG_MESSAGE);

            }
        } catch (JSONException e) {
            e.printStackTrace();
        } 
        return null;            
    }
    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog once product deleted
        pDialog.dismiss();
        if (file_url != null){
            Toast.makeText(Loginpage.this, file_url, Toast.LENGTH_LONG).show();
        }

    }

}

public JSONObject makeHttpRequest(String url,String method,             列表参数){

    // Making HTTP request
    try {

        // check for request method
        if(method == "POST"){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        }else if(method == "GET"){
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }           

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}

5 个答案:

答案 0 :(得分:1)

String username = user.getText().toString();在onPreExecute方法中移动此行..u无法在doInBackground方法中处理Ui

答案 1 :(得分:0)

我认为这些台词 String username = user.getText().toString(); String password = pass.getText().toString();导致问题。

您无法在AsyncTask中访问或修改UI。

你可以在onPreExecute()之前做到这一点 (更喜欢全局声明变量)

或在调用.execute("")并将用户名和密码作为args传递之前,即.execute(username,password);。然后在doInBackground中,你可以把它作为args [0]和args [1]。

答案 2 :(得分:0)

Hope this might help you.
 int sucess;//declare in global
 @Override

 protected String doInBackground(String... args)
   {

    // TODO Auto-generated method stub
     // Check for success tag

     String username = user.getText().toString();
     String password = pass.getText().toString();

        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("username", username));
        params.add(new BasicNameValuePair("password", password));
        // getting product details by making HTTP request
        JSONObject json = jsonParser.makeHttpRequest(
               LOGIN_URL, "POST", params);
        try
        {
        success = json.getInt(TAG_SUCCESS);
        }
        catch (Exception e) 
        {
    e.printStackTrace();
    }
        return null;
        }
        protected void onPostExecute(String file_url) {
    pDialog.dismiss();//progress dialog pDialog
        if (success == 1) {    
            Intent i = new Intent(Loginpage.this, Propertyapp.class);
            startActivity(i);
           finish();
        }
    } 

}

答案 3 :(得分:0)

全球宣布意图&amp;在oncreate()中初始化,

Intent i ;

i= new Intent(Loginpage.this, Propertyapp.class);

根据您的要求使用它

            startActivity(i);

答案 4 :(得分:0)

你的问题

String username = user.getText().toString();
String password = pass.getText().toString();

您无法在后台线程中执行UI更新。将它们移出。
您可以使用onPreExecute()方法,或者只是将用户名和密码传递给AsyncTask()。

public class YourAsyncTask extends AsyncTask<String, Integer, String>{

        @Override
        protected String doInBackground(String... params) {
            String username = params[0];
            String password = params[1];
                         ....
         }
}