通过Android使用RESTful Web服务编写数据

时间:2013-12-25 06:33:26

标签: java android post

我正在开发android应用程序。我们的java开发团队编写了restfull web服务 读取和写入data.i成功读取数据并显示到device.i中使用以下android代码插入数据,但它无法正常工作。

public class MainActivity extends Activity 
{

    ProgressDialog pd;
    List<NameValuePair>list;
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new Mytask().execute();   
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    public class Mytask extends AsyncTask<String,String,String>
    {


        @Override
        protected void onPostExecute(String result) 
        {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            Toast.makeText(getBaseContext(), "Inser Record Succesfully", Toast.LENGTH_LONG).show();
            pd.dismiss(); 

        }

        @Override
        protected void onPreExecute() 
        {
            // TODO Auto-generated method stub
            super.onPreExecute();
            pd=new ProgressDialog(MainActivity.this);
            pd.setMessage("Please Wait");
            pd.show();
        }

        @Override
        protected String doInBackground(String... params) 
        {
            // TODO Auto-generated method stub
            pushdata();
            return null;

        }

    }
    public void pushdata()
    {
        try
        {
            HttpClient client=new DefaultHttpClient();
            HttpPost post=new HttpPost("http://192.168.1.239:8080/KesariRating/rating/add");
            // add data to url
            list=new ArrayList<NameValuePair>(5);
            list.add(new BasicNameValuePair("exce","e"));
            list.add(new BasicNameValuePair("vgood","null"));
            list.add(new BasicNameValuePair("good","null"));
            list.add(new BasicNameValuePair("poor","null"));
            list.add(new BasicNameValuePair("fair","null"));
            post.setEntity(new UrlEncodedFormEntity(list));
            HttpResponse response=client.execute(post);
            HttpEntity entity=response.getEntity();
        }
        catch(Exception e)
        {
            Log.d("Error in Push","",e);

        }
    }
}

你能告诉我在那段代码中我做错了什么。我认为我们需要创建类对象并发送给它然后它会工作。那么如何在上面的代码中创建类对象并发送给它。我还发送了Web服务的完整源代码。这是控制器

public class RatingController 
{


    @ResponseBody
    @RequestMapping(value="/hello/{name}",method=RequestMethod.GET)
    public static String sayhello(@PathVariable String name)
    {   
        return "Hello "+name ;
    }

    @ResponseBody
    @RequestMapping(value="/sayhello/{name}",method=RequestMethod.GET)
    public static String add(@PathVariable String name)
    {   
    RatingCore ratingCore = new RatingCore();
    ratingCore.setExcellent("t");
    ratingCore.setVgood("t");

        RatingOperation.addRating(ratingCore);
        return "Hello "+name ;
    }

    @ResponseBody
    @RequestMapping(value="/add",method=RequestMethod.POST)
    public static boolean add(@RequestBody RatingCore objRatingCore)
    {   

        return RatingOperation.addRating(objRatingCore);      

    }
    @ResponseBody
    @RequestMapping(value="/getcount",method=RequestMethod.GET)
    public static RatingCore getCount()
    {   

        return RatingOperation.getCount();    

    }

}

这是java代码

public class RatingCore {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String excellent;
    private String vgood;
    private String good;
    private String poor;
    private String fair;
    private Date timestamp;

    public RatingCore() {

    }

    public RatingCore(int id, String excellent, String vgood, String good,

    String poor, String fair, Timestamp timestamp) {
        super();
        this.id = id;
        this.excellent = excellent;
        this.vgood = vgood;
        this.good = good;
        this.poor = poor;
        this.fair = fair;
        this.timestamp = timestamp;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getExcellent() {
        return excellent;
    }

    public void setExcellent(String excellent) {
        this.excellent = excellent;
    }

    public String getVgood() {
        return vgood;
    }

    public void setVgood(String vgood) {
        this.vgood = vgood;
    }

    public String getGood() {
        return good;
    }

    public void setGood(String good) {
        this.good = good;
    }

    public String getPoor() {
        return poor;
    }

    public void setPoor(String poor) {
        this.poor = poor;
    }

    public String getFair() {
        return fair;
    }

    public void setFair(String fair) {
        this.fair = fair;
    }

    public Date getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(Date timestamp) {
        this.timestamp = timestamp;
    }

}

1 个答案:

答案 0 :(得分:0)

我的代码是将一些数据发送到Server数据库,我希望它能帮到你

    private void validat_user(String stg1, String stg2,String stg3, String stg4,String stg5, String stg6,String stg7, String stg8,String stg9, String stg10,String stg11)
    {

        WebServiceTask wst = new WebServiceTask(WebServiceTask.POST_TASK, this, "Authentication in progress...");

        wst.addNameValuePair("A_ID", stg1);
        wst.addNameValuePair("A_NAME", stg2);
        wst.addNameValuePair("A_PWD1", stg3);
        wst.addNameValuePair("A_JOIN", stg4);
        wst.addNameValuePair("A_END", stg5);
        wst.addNameValuePair("A_COURSE", stg6);
        wst.addNameValuePair("A_FACID", stg7);
        wst.addNameValuePair("A_SESSION", stg8);
        wst.addNameValuePair("A_BATCH", stg9);
        wst.addNameValuePair("A_BRANCH1", stg10);
        wst.addNameValuePair("A_GENDER", stg11);
        wst.execute(new String[] { SERVICE_URL });

    }
    @SuppressWarnings("deprecation")
    public void no_net()
    {
        display( "No Network Connection");
        final AlertDialog alertDialog = new AlertDialog.Builder(Staff.this).create();
        alertDialog.setTitle("No Internet Connection");
        alertDialog.setMessage("You don't have internet connection.\nElse please check the Internet Connection Settings.");
        //alertDialog.setIcon(R.drawable.error_info);
        alertDialog.setCancelable(false);
        alertDialog.setButton("Close", new DialogInterface.OnClickListener() 
        {
            public void onClick(DialogInterface dialog, int which)
            {   
                alertDialog.cancel();
                Staff.this.finish();
                System.exit(0);
            }
        });
        alertDialog.setButton2("Use Local DataBase", new DialogInterface.OnClickListener() 
        {
            public void onClick(DialogInterface dialog, int which)
            {
                display( "Accessing local DataBase.....");
                alertDialog.cancel();
            }
        });
        alertDialog.show();
    }

    private class WebServiceTask extends AsyncTask<String, Integer, String> {

        public static final int POST_TASK = 1;

        private static final String TAG = "WebServiceTask";

        // connection timeout, in milliseconds (waiting to connect)
        private static final int CONN_TIMEOUT = 3000;

        // socket timeout, in milliseconds (waiting for data)
        private static final int SOCKET_TIMEOUT = 5000;

        private int taskType = POST_TASK;
        private Context mContext = null;
        private String processMessage = "Processing...";

        private ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();

        private ProgressDialog pDlg = null;

        public WebServiceTask(int taskType, Context mContext, String processMessage) {

            this.taskType = taskType;
            this.mContext = mContext;
            this.processMessage = processMessage;
        }

        public void addNameValuePair(String name, String value) {

            params.add(new BasicNameValuePair(name, value));
        }