Android使用okhttp 響應Post請求 使用線程


1.在libs中導入okhttp-2.7.5.jar和okio-1.11.0.jar。

2.post請求

public void getData(){
new Thread(new Runnable() {
@Override
public void run() {
try {
String s = "{\"action\":\"get\",\"object\":\"light\"}";
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),s);
Request request = new Request.Builder()
.post(body)
.url("http://dev1.cn:xxxx")
.build();
Response response = null;

response = client.newCall(request).execute();
if (response.isSuccessful()){
Log.d("response.code()==",response.code()+"");
Log.d("response.message()==",response.message());
Log.d("res==",response.body().string());
}
} catch (Exception e) {
e.printStackTrace();
}

}
}).start();
};

3.在onCreate 中默認界面啟動 

4.需要在清單文件中

<uses-permission android:name="android.permission.INTERNET"/>



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM