packagecom.example.mengweixue.androidokhttp;
importandroid.support.v7.app.AppCompatActivity;
importandroid.os.Bundle;
importandroid.util.Log;
importandroid.view.View;
importandroid.widget.Toast;
importcom.squareup.okhttp.Call;
importcom.squareup.okhttp.Callback;
importcom.squareup.okhttp.FormEncodingBuilder;
importcom.squareup.okhttp.OkHttpClient;
importcom.squareup.okhttp.Request;
importcom.squareup.okhttp.RequestBody;
importcom.squareup.okhttp.Response;
importjava.io.IOException;
public classMainActivityextendsAppCompatActivity {
private final staticStringTAG="TestActivity";
private finalOkHttpClientclient=newOkHttpClient();
@Override
protected voidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//GET请求----方法
private voidenqueue(){
Request request =newRequest.Builder()
.url("xx0")
.build();
client.newCall(request).enqueue(newCallback() {
@Override
public voidonFailure(Request request,IOException e) {
}
@Override
public voidonResponse(Response response)throwsIOException {
//NOT UI Thread
if(response.isSuccessful()){
System.out.println(response.code());
System.out.println(response.body().string());
}
}
});
}
//get请求---请求
public voidgetactionnet(View view){
Toast.makeText(MainActivity.this,"Get",Toast.LENGTH_SHORT).show();
newThread(newRunnable() {
@Override
public voidrun() {
try{
enqueue();
}catch(Exception e) {
e.printStackTrace();
}
}
}).start();
}
//post请求-----请求
public voidpostactionnet(View view){
Toast.makeText(MainActivity.this,"POST",Toast.LENGTH_SHORT).show();
newThread(newRunnable() {
@Override
public voidrun() {
try{
postData();
}catch(Exception e) {
e.printStackTrace();
}
}
}).start();
}
//post请求----方法
public voidpostData() {
RequestBody formBody =newFormEncodingBuilder()
.add("username","111111")
.add("password","111111")
.add("client","ios")
.build();
Request request =newRequest.Builder()
.url("xx")
.post(formBody)
.build();
client.newCall(request).enqueue(newCallback() {
@Override
public voidonFailure(Request request,IOException e) {
}
@Override
public voidonResponse(Response response)throwsIOException {
//NOT UI Thread
if(response.isSuccessful()) {
System.out.println(response.code());
System.out.println(response.body().string());
}
}
});
}
}