一个关于Get和Post的文章:https://blog.csdn.net/koozxcv/article/details/51023628
OkHttp就是一个实现使用HTTP访问网络的方式,其中包含Get和Post两种:
首先导包:
compile 'com.squareup.okhttp3:okhttp:3.4.1'
接着我们写一个布局进行操作和显示结果:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.administrator.happyandroid.Activity.OkHttpActivity">
<Button
android:id="@+id/send_Okhttp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="send"/>
<TextView
android:id="@+id/get_Okhttp"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
</LinearLayout>
下面是Activity中的代码:
public class OkHttpActivity extends AppCompatActivity {
private final int OKHTTP_GET = 0;
private Button send_http;
private TextView get_http;
String responseData;
//接受信息,改变UI(UI只能在主线程中修改,否则报错)
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case OKHTTP_GET:
get_http.setText(responseData);
break;
default:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ok_http);
send_http = findViewById(R.id.send_Okhttp);
get_http = findViewById(R.id.get_Okhttp);
//点击事件发送OkHttp请求
send_http.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendRequestWithOkHttp();
}
});
//设置TextView可滚动
get_http.setMovementMethod(new ScrollingMovementMethod());
}
private void sendRequestWithOkHttp() {
//请求网络操作必须要在子线程中进行(主线程会报错)
new Thread(new Runnable() {
@Override
public void run() {
try {
//创建一个OkHttpClient实例
OkHttpClient client = new OkHttpClient();
//如果要发起一条HTTP请求,就需要创建一个Request对象
//GET请求
// Request request = new Request.Builder()
// .url("http://www.baidu.com")
// .build();
//POST请求(需要一个RequestBody来存放需要提交的参数)
RequestBody requestBody = new FormBody.Builder()
.add("arg1","123")
.add("arg2","123456")
.build();
Request request = new Request.Builder()
.url("http://www.baidu.com")
.post(requestBody)
.build();
//调用newCall()方法来创建一个Call对象,并调用他的execute()方法来发送请求并获取服务器返回的数据
Response response = client.newCall(request).execute();
//得到返回的服务器的数据内容
responseData = response.body().string();
//在获取到服务器返回的数据之后发送消息改变UI
Message message = new Message();
message.what = OKHTTP_GET;
handler.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
返回的结果就不重要了,因为Post的请求是随便输入的,看一下返回的代码应该是返回“页面不存在_百度搜索”