OkHttp的get post 以及同步请求Demo

依赖:

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="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;
        }
    }
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值