1.创建OkHttpClient 对象
2.创建Request 对象 发送http请求
3.通过.xxx 给Request 对象连缀方法
4.newCall 方法 发送请求 和获取服务器返回的数据
/**
* okHttp发送网络请求
*/
public class MainActivity extends AppCompatActivity implements View.OnClickListener
{
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button send = findViewById(R.id.button);
textView = findViewById(R.id.textView);
send.setOnClickListener(this);
}
@Override
public void onClick(View v)
{
if (v.getId() == R.id.button) {
sendRequestWithOkHttp();
}
}
private void sendRequestWithOkHttp()
{
// 开子线程
new Thread(new Runnable()
{
@Override
public void run()
{
try {
OkHttpClient client = new OkHttpClient(); // 创建OkHttpClient 实例
//post 请求 时候传递的参数
RequestBody requestBody = new FormBody.Builder()
.add("name","xiaoming")
.add("pwd","123")
.build();
Request request = new Request.Builder() // 发送请求并获取服务器返回数据(request)
.url("http://www.baidu.com")
.post(requestBody) // 不带参数默认为get请求
.build();
Response response = client.newCall(request).execute();// 返回数据的具体内容
String responseData = response.body().string();
showBuffer(responseData);
}
catch (Exception e) {
}
}
}).start();
}
private void showBuffer(final String response)
{
// ui操作 更新ui
runOnUiThread(new Runnable()
{
@Override
public void run()
{
textView.setText(response);
}
});
}
}
本文介绍了一个使用OkHttp库发送POST请求到服务器并接收响应的Android应用示例。通过创建OkHttpClient实例,并构建带有参数的RequestBody对象,文章展示了如何发起网络请求及处理返回的数据。
476

被折叠的 条评论
为什么被折叠?



