用AndroidStudio,先导入jar包
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile group: 'com.squareup.okhttp3', name: 'okhttp', version: '3.8.0'
}
这里贴出一个注册的实例,分别采用了get和post两种方式
registerBt = (Button) findViewById(R.id.register_bt);
registerBt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
phoneNumEt.getText();
pwdEt.getText();
// haveGetUrlReg();
havaPostUrlReg();
}
});
······
······
public void haveGetUrlReg() {
final Request request=new Request.Builder()
.get()
.tag(this)
.url("http://192.168.0.60:8080/zjcc/student/mobile/register.do?phone=12045689345&pwd=123")
.build();
new Thread(new Runnable() {
@Override
public void run() {
Response response = null;
try {
response = client.newCall(request).execute();
if (response.isSuccessful()) {
Log.i("WY","打印GET响应的数据:" + response.body().string());
} else {
throw new IOException("Unexpected code " + response);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
public void havaPostUrlReg() {
FormBody body = new FormBody.Builder()
.add("phone", phoneNumEt.getText().toString())
.add("pwd", pwdEt.getText().toString())
.build();
final Request request = new Request.Builder()
.url("http://192.168.0.60:8080/zjcc/student/mobile/register.do")
.post(body)
.build();
new Thread(new Runnable() {
@Override
public void run() {
Response response = null;
try {
response = client.newCall(request).execute();
if (response.isSuccessful()) {
Log.i("WY","打印POST响应的数据:" + response.body().string());
} else {
throw new IOException("Unexpected code " + response);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
上面是两种简单的网络请求的写法。