安卓开发笔记——安卓Post方法提交数据至服务器后服务器返回数据至客户端

具体代码为:

public void sendGetHttpRequest(){
OkHttpClient client = new OkHttpClient();
String username = et_username.getText().toString().trim();
String userpassword = et_password.getText().toString().trim();
RequestBody requestBody = new FormBody.Builder()
.add( “username”, username )
.add( “password”, userpassword )
.build();
Request request = new Request.Builder()
.url( “http://…” )
.post( requestBody )
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(okhttp3.Call call,IOException e) {
Log.d(TAG,“获取数据失败”+e.toString());
}
@Override
public void onResponse(okhttp3.Call call,Response response) throws IOException {
if(response.isSuccessful()){ //回调的方法执行在子线程
Log.d(TAG,“获取数据成功”);
Log.d(“Test”,“response.code()"+response.code());
final String str = response.body().string();
Log.d(TAG,"response.body().string()
”+str);
runOnUiThread(new Runnable() {
@Override
public void run() {
result.setText( str );
}
});
}
}
} );
}

注:runOnUiThread()方法的作用是将当前线程切换到主线程。

猜你喜欢

转载自blog.csdn.net/qq_38233258/article/details/88627868
今日推荐