android send http post request - correct way -
good morning together,
i found helpful tutorial making http post request android. code works fine, know, if code best way this, or if yo have ideas, how can optimize it.
private class postclass extends asynctask<string, string, string> { context context; public postclass(context c){ this.context = c; } @override protected string doinbackground(string... params) { try { url url = new url("xxxx"); httpurlconnection connection = (httpurlconnection)url.openconnection(); string urlparameters = "xxx"; connection.setrequestmethod("post"); connection.setdooutput(true); dataoutputstream dstream = new dataoutputstream(connection.getoutputstream()); dstream.writebytes(urlparameters); dstream.flush(); dstream.close(); bufferedreader br = new bufferedreader(new inputstreamreader(connection.getinputstream())); final string response = br.readline(); br.close(); return response; } catch (malformedurlexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } return null; } protected void onpostexecute(string result){ toast.maketext(getbasecontext(), result, toast.length_short).show(); } }
based on frequency of synchronization , use volley. also, use following code need send multiple parameters in post request.
httpclient httpclient = new defaulthttpclient(); string responsestr=""; string url=constants.api_url;#url request needs sent httppost httppost = new httppost(url); try { // add data list<namevaluepair> namevaluepairs = new arraylist<namevaluepair>(); namevaluepairs.add(new basicnamevaluepair("id", pick_up_id)); namevaluepairs.add(new basicnamevaluepair("driver_photo", strphoto));#image in form of base64 string need send httppost.setentity(new urlencodedformentity(namevaluepairs)); // execute http post request httpresponse response = httpclient.execute(httppost); int responsecode = response.getstatusline().getstatuscode(); switch(responsecode) { case 200: httpentity entity = response.getentity(); if(entity != null) { string responsebody = entityutils.tostring(entity); responsestr=responsebody; } break; } } catch (clientprotocolexception e) { // todo auto-generated catch block } catch (ioexception e) { // todo auto-generated catch block } system.out.println("this response "+responsestr);
Comments
Post a Comment