您的位置:首页 > 理论基础 > 计算机网络

OkHttp的get post 以及同步请求Demo

2017-11-07 19:40 453 查看
依赖:

compile 'com.squareup.okhttp3:okhttp:3.9.0'

权限:

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>

<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:id="@+id/showtv"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/getbut"
android:text="getbut"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/postbut"
android:text="postbut"
/>
<Button
android:layout_width=[b]"match_parent"
android:layout_height="wrap_content"
android:id="@+id/but"
android:text="同步"
/>
</LinearLayout>
Activity代码:
package com.example.okhttp;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

private TextView tv;
private Button but,getbut,postbut;
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);

String str = (String) msg.obj;
tv.setText(str);
}
};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

initview();

getbut.setOnClickListener(this);
postbut.setOnClickListener(this);
but.setOnClickListener(this);

}

private void initview() {
tv = (TextView) findViewById(R.id.showtv);
but = (Button) findViewById(R.id.but);
getbut = (Button) findViewById(R.id.getbut);
postbut = (Button) findViewById(R.id.postbut);

}

@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.getbut:
// 1.OKHttpClient对象
OkHttpClient client = new OkHttpClient.Builder().build();
//Request对象 子线程
Request request = new Request.Builder()
.get()
.url("http://www.wuxirui.com/")
.build();
//Call对象
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e("TAG", "get请求失败: " + e.getMessage());
}

//成功
@Override
public void onResponse(Call call, Response response) throws IOException {

//不是toString
String text = response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
tv.setText("请求成功");
}
});
}
});

break;

case R.id.postbut:
// 1.OkHttpClient对象
OkHttpClient okHttpClient = new OkHttpClient();
// 2.提供post请求需要的body对象
FormBody body = new FormBody.Builder()
.add("mobile", "15340986701")
.add("password", "123456")
.build();

//Request对象
Request build = new Request.Builder()
.post(body)
.url("http://120.27.23.105/user/login")
.build();
//Call对象
Call postCall = okHttpClient.newCall(build);
// 5.进行网络请求,enqueue方法,是异步请求
postCall.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i("TAG", "post失败 " + e.getMessage());
}

@Override
public void onResponse(Call call, Response response) throws IOException {
Log.i("TAG", "post成功 " + response.body().string());
runOnUiThread(new Runnable() {
@Override
public void run() {
tv.setText("登录成功");
}
});
}
});
break;

//同步加载
case R.id.but:
new Thread(){
@Override
public void run() {
super.run();

OkHttpClient okhttp = new OkHttpClient();
Request requestbuild = new Request.Builder()
.get()
.url("http://www.wuxirui.com/")
.build();

Call lastcall = okhttp.newCall(requestbuild);

try {
Response execute = lastcall.execute();
String text = execute.body().string();

Log.i("TAG", "同步: " + text);

Message message = handler.obtainMessage();
message.what=1;
message.obj=text;
message.sendToTarget();
} catch (Exception e) {
e.printStackTrace();
}

}
}.start();
break;
}
}
}




                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐