/**
* 发送网络请求
* @param url 网络地址
* @param username 用户名
* @param password 密码
* @param callback 请求返回
*/
包:implementation ‘com.squareup.okhttp3:okhttp:3.12.0’
protected void sendRequest(String url,String username,String password,Callback callback){
RequestBody requestBody=new FormBody.Builder().add("city",username)
.add("appKey",password)
.build();
Request request=new Request.Builder().url(url).post(requestBody).build();
OkHttpClient okHttpClient=new OkHttpClient();
okHttpClient.newCall(request).enqueue(callback);
}
private void getrequest(){
OkHttpClient client=new OkHttpClient();
final Request request=new Request.Builder().get().url("http://www.baidu.com").build();
Call call=client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Toast.makeText(MainActivity.this,e.getMessage(),Toast.LENGTH_LONG).show();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String str=response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
tv.setText(str);
}
});
}
});
}
private void getimg(){
OkHttpClient client=new OkHttpClient();
final Request request=new Request.Builder().get().url("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1542603500099&di=05ca140c2f6ce7c73076ef3debb98bf0&imgtype=0&src=http%3A%2F%2Fwww.17qq.com%2Fimg_qqtouxiang%2F75142881.jpeg").build();
Call call=client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Toast.makeText(MainActivity.this,e.getMessage(),Toast.LENGTH_LONG).show();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
InputStream inputStream=response.body().byteStream();
final Bitmap bitmap= BitmapFactory.decodeStream(inputStream);
runOnUiThread(new Runnable() {
@Override
public void run() {
img.setImageBitmap(bitmap);
}
});
}
});
}
private void postrequest(String name,String pass){
OkHttpClient client=new OkHttpClient();
RequestBody formBody=new FormBody.Builder()
.add("username",name)
.add("password",pass)
.build();
Request request=new Request.Builder().post(formBody).url("http://115.28.211.9:8080/exame/reg_register").build();
Call call=client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Toast.makeText(MainActivity.this,e.getMessage(),Toast.LENGTH_LONG).show();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String str=response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
tv.setText(str);
Toast.makeText(MainActivity.this,"post请求成功",Toast.LENGTH_SHORT).show();
}
});
}
});
}
}