java - How to send HTTP request from android app to Heroku -
i have android app uses twilio sdk , hosted heroku server. i'm trying push button in app send http request heroku send rest api request twilio update twiml url. current way i'm trying send the http request not working. have looked through of examples find , none of them show how function. know how this? in advance.
this code trying send http request heroku
holdbutton.setonclicklistener(new view.onclicklistener() { @override public void onclick(view view) { httpclient httpclient = new defaulthttpclient(); httppost httppost = new httppost("http://yourappnamehere.herokuapp.com/hello"); try { // execute http post request httpresponse response = httpclient.execute(httppost); httpentity ht = response.getentity(); bufferedhttpentity buf = new bufferedhttpentity(ht); inputstream = buf.getcontent(); bufferedreader r = new bufferedreader(new inputstreamreader(is)); stringbuilder total = new stringbuilder(); string line; while ((line = r.readline()) != null) { total.append(line); } } catch (clientprotocolexception e) { // todo auto-generated catch block } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } //setting toast see if being initiated toast.maketext(getbasecontext(), "why wont work!", toast.length_short).show(); } ; });
this updated code including volley library
holdbutton.setonclicklistener(new view.onclicklistener() { @override public void onclick(view view) { //setting request queue volley api //requestqueue mrequestqueue; // instantiate cache cache cache = new diskbasedcache(getcachedir(), 1024 * 1024); // 1mb cap // set network use httpurlconnection http client. network network = new basicnetwork(new hurlstack()); // instantiate requestqueue cache , network. mrequestqueue = new requestqueue(cache, network); // start queue mrequestqueue.start(); string url = "http://yourappnamehere.herokuapp.com/hello"; // formulate request , handle response. stringrequest stringrequest = new stringrequest(request.method.post, url, new response.listener<string>() { @override public void onresponse(string response) { // response } }, new response.errorlistener() { @override public void onerrorresponse(volleyerror error) { // handle error } }); // add request requestqueue. mrequestqueue.add(stringrequest); toast.maketext(getbasecontext(), "why wont work!", toast.length_short).show(); } ; });
i suggest using library google volley pretty slick https://developer.android.com/training/volley/index.html
httprequest deprecated api level 22. best practice avoid using that. use java.net.httpurlconnection instead.
however, if still want use it, above code needs run on thread other ui thread mentioned in comment above.
Comments
Post a Comment