无法使用webservice在android中发布数据

时间:2016-04-10 07:43:44

标签: android web-services

以下是我尝试执行的代码snipets但是我收到FatalErrorException但是当我尝试在浏览器中使用url运行webservice代码时

http://localhost:8082/WebServices/Rest/courseService/LoginInfo/a:a

它运行得很完美并且给出了完美的结果但是我不能用android使用下面的代码

我有这个ServiceHandlerClass,它将处理所有的webservice请求

public class ServiceHandler {
    static String response = null;
    public final static int GET = 1;
    public final static int POST = 2;

    // Default Constructor
    public ServiceHandler() {
        // TODO Auto-generated constructor stub
    }

    public String makeServiceCall(String url, int method) {
        return this.makeServiceCall(url, method, null);
    }

    public String makeServiceCall(String url, int method, String parameter) {

        try {
            // http client
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpEntity httpEntity = null;
            HttpResponse httpResponse = null;

            // Checking http request method type
            if (method == POST) {
                HttpPost httpPost = new HttpPost(url);

                httpResponse = httpClient.execute(httpPost);

            } else if (method == GET) {
                // appending params to url
                if (parameter != null) {
                    url += parameter;
                }
                HttpGet httpGet = new HttpGet(url);
                httpResponse = httpClient.execute(httpGet);
                Log.d("Parmaeter2",parameter);

            }
            httpEntity = httpResponse.getEntity();
            response = EntityUtils.toString(httpEntity);

        }  catch (Exception e){
                Log.d("Service Handler Error",e.toString());
        }

        return response;

    }

}

但我在httpResponse = httpClient.execute(httpPost);

上收到错误
This is my async DoInbackground code

    class DoInBackground extends AsyncTask<Void, Void, Void>
    {
        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Please Wait...");
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            // TODO Auto-generated method stub
            ServiceHandler sh = new ServiceHandler();
            String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET,ParameterToPass);
            Log.d("Response: ", "> " + jsonStr);

            //PojoProduct item = null;
            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);
                    jsonarray = jsonObj.getJSONArray(TAG_CONTACTS);

                    for (int i = 0; i < jsonarray.length(); i++) {
                        JSONObject c = jsonarray.getJSONObject(i);
                        msg = c.getString(TAG_MESSAGE);

                    }


                } catch (Exception e) {
                    // TODO: handle exception
                }
            } else {

            }


            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);

            if(!msg.equals("false"))
            {

                SharedPreferences.Editor editor = sharedpreferences.edit();

                editor.putString("Username", txtUserName.getText().toString().trim());
                editor.putString("Password", txtPassword.getText().toString().trim());
                editor.commit();

                Intent i=new Intent(MainActivity.this,Category.class);
                finish();
                startActivity(i);
                //System.out.println("Successful");
                //Toast.makeText(getBaseContext(),"SuccessFul", Toast.LENGTH_LONG).show();
            }
            else
            {
                txtUserName.setText("");
                txtPassword.setText("");
                Toast.makeText(getBaseContext(),"Please Enter Valid UserName & Password.", Toast.LENGTH_LONG).show();
            }
            pDialog.dismiss();
        }

    }

以下是错误

04-10 03:30:44.850: E/AndroidRuntime(5559): Caused by: java.lang.NoSuchMethodError: org.apache.http.impl.client.DefaultHttpClient.execute
04-10 03:30:44.850: E/AndroidRuntime(5559):     at com.example.shoponchat.ServiceHandler.makeServiceCall(ServiceHandler.java:52)

1 个答案:

答案 0 :(得分:0)

不推荐使用HttpClient,如果你开始使用HttpURLConnection,那将是最好的做法。 我提供的代码可以帮助您了解如何使用HttpURLConnection .. 问我是否需要任何其他信息:)

        private class GetUsers extends AsyncTask<Void, Void, String>  {

    String url_ = "Provide url here";
    HttpURLConnection conn;

    @Override
    protected String doInBackground(Void... params) {
        try {
            URL url = new URL(url_);

            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);

            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            SharedPreferences userInfo = getSharedPreferences("mypref", 0);
            String urlParameters = "username="
                    + URLEncoder
                            .encode(userInfo.getString("username", "Null"),
                                    "UTF-8");
            writer.write(urlParameters);
            writer.flush();
            writer.close();
            os.close();

            int responseCode = conn.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {

                BufferedReader bufferedReader = new BufferedReader(
                        new InputStreamReader(conn.getInputStream()));
                StringBuilder stringBuilder = new StringBuilder();
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuilder.append(line + '\n');
                }

                String jsonString = stringBuilder.toString();
                System.out.println(jsonString);
                jsonArray = new JSONArray(jsonString);

                return "User List Loaded succesfully";

            } else {

                return "Error occured in Registration";

            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
            System.out.println("Exception1");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Exception2");
        } catch (JSONException e) {
            e.printStackTrace();
            System.out.println("Exception3");
        } finally {
            conn.disconnect();
        }
        return "Null";
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        String[] names = new String[jsonArray.length()];
        for (int i = 0; i < jsonArray.length(); i++) {
            try {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String username = jsonObject.getString("username");
                names[i] = username;
            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println("Json array exception");
            }

        }
    }

}