OkHttpClient in android -
i wrote following code send request server , getting response server. when run following code can not work me. wrote code based this link.
public class mainactivity extends activity { @override protected void oncreate(bundle bundle) { super.oncreate(bundle); setcontentview(r.layout.activity); button button = (button)findviewbyid(r.id.bu1); button.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { try { run(); } catch (exception e) { toast.maketext(getapplicationcontext(),"error",toast.length_long).show(); } } }); } private final okhttpclient client = new okhttpclient(); public void run() throws exception { request request = new request.builder() .url("http://127.0.0.1:8080/file.php") .build(); call call = client.newcall(request); response response = call.execute(); if (!response.issuccessful()) { throw new ioexception("unexpected code " + response); } string text = response.body().string(); toast.maketext(getapplicationcontext(), text, toast.length_short).show(); } }
usually error because:
doesn't have internet permission
it in ui thread
you can confirm in logcat.
solution:
- add in manifest
<uses-permission android:name="android.permission.internet" />
you must run in other thread or using async 1 this:
public void run() { request request = new request.builder() .url("http://127.0.0.1:8080/file.php") .build(); call call = client.newcall(request); call.enqueue(new callback() { @override public void onfailure(request request, ioexception e) { log.d("tag", "failed: " + e.getmessage()); } @override public void onresponse(response response) throws ioexception { log.d("tag", "ok: " + response.body().string()); } } }
Comments
Post a Comment