使用步骤:
1、在线集成依赖包并添加网络权限:
grade中:
compile 'com.squareup.okhttp3:okhttp:3.6.0'
manifest中:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
2、MainAcvitity中调试代码:
public class MainActivity extends AppCompatActivity {
private EditText et_username,et_password;
private Button btn_login;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_username= (EditText) findViewById(R.id.et_username);
et_password= (EditText) findViewById(R.id.et_password);
btn_login= (Button) findViewById(R.id.btn_login);
btn_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
loginByPost();
}
});
}
/**
* 默认get请求,不需要请求体
*/
private void login(){
OkHttpClient okHttpClient=new OkHttpClient();
String username = et_username.getText().toString();
String password = et_password.getText().toString();
Request request=new Request.Builder().url("http://192.168.15.114:8080/HttpTest/Login?username="
+ username + "&password=" + password).build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String res=response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),res,Toast.LENGTH_SHORT).show();
}
});
}
});
}
/**
* 自定义post请求
* 需要增加RequestBody来存储请求的参数信息;
* 在Request.Builder中增加post(RequestBody)调用。 *
*/
private void loginByPost(){
OkHttpClient client=new OkHttpClient();
String username = et_username.getText().toString();
String password = et_password.getText().toString();
RequestBody requestBody=new FormBody.Builder().add("username",username).add("password",password).build();
Request request=new Request.Builder().url("http://192.168.15.114:8080/HttpTest/Login")
.post(requestBody).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String res=response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),res,Toast.LENGTH_SHORT).show();
}
});
}
});
}