//首页先添加依赖,因一般要解析,同时添加gson依赖
compile 'com.squareup.okhttp3:okhttp:3.6.0'
compile 'com.squareup.okio:okio:1.11.0'
compile 'com.google.code.gson:gson:2.2.4'
//封装的工具类
package com.bawei.com.day_08okhttp;
import android.os.Handler;
import android.os.Message;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/**
* Created by lenovo on 2018/1/3.
*/
public class OKHttpUitls {
private OKHttpGetListener oKHttpGetListener;
MyHandler myhandler=new MyHandler();
**//get请求**
public void get(String url){
OkHttpClient client = new OkHttpClient();
//创建请求对象
Request build = new Request.Builder().url(url).build();
//创建Call请求队列
//请求都是放到一个队列里面的
Call call = client.newCall(build);
//开始请求
call.enqueue(new Callback() {
//失败,方法都是在子线程里面,不能直接更新UI
@Override
public void onFailure(Call call, IOException e) {
Message message = myhandler.obtainMessage();
message.obj="请求失败";
message.what=0;
myhandler.sendMessage(message);
}
// 成功的法都是在子线程里面,不能直接更新UI
@Override
public void onResponse(Call call, Response response) throws IOException {
Message message = myhandler.obtainMessage();
String josn = response.body().string();
message.obj=josn;
//用handler发送
message.what=1;
myhandler.sendMessage(message);
}
});
}
}
//post请求的方法
public void postJson(String surl){
//创建OkHttpClient,也就是okhttp的客户端
OkHttpClient client=new OkHttpClient();
//创建post请求的formbody 关键代码 键值对配置
FormBody formBody=new FormBody.Builder()
.add(“name”,”aa”)
.add(“ket”,”bb”)
.build();
//创建请求
Request request=new Request.Builder().url(surl).post(formBody).build();
//设置回调
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
//失败,成功的方法都是在子线程里面,不能直接更新UI
Message msg=new Message();
msg.obj="请求失败";
//用handler发送
msg.what=0;
myhandler.sendMessage(msg);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Message msg=new Message();
msg.obj="成功";//获取解析的数据
msg.what=1;
myhandler.sendMessage(msg);
}
});
}
//使用接口回到,将数据返回
public interface OKHttpGetListener{
void error(String error);
void success(String json);
}
//给外部调用的类
public void setOnOKHttpGetListener(OKHttpGetListener oKHttpGetListener){
this.oKHttpGetListener=oKHttpGetListener;
}
//使用Handler,将数据在主线程返回
class MyHandler extends Handler{
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
int i= (int) msg.what;
if(i==0){
String str= (String) msg.obj;
oKHttpGetListener.error(str);
}
if(i==1){
String json= (String) msg.obj;
oKHttpGetListener.success(json);
}
}
}
**//mainActivity中调用方法,并使用接口回调**
package com.bawei.com.day_08okhttp;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private String key = "9178d0af064827ca20e348cd57fdccba";
private String url = "http://v.juhe.cn/weather/index?format=2&cityname=%E8%8B%8F%E5%B7%9E&key="+key;
private Button get;
private ListView lv;
List<Bean.ResultBean.FutureBean> list= new ArrayList<Bean.ResultBean.FutureBean>();
private MyBaseAdapter my;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
//方法
private void initViews() {
//获取id
get = (Button) findViewById(R.id.get);
lv = (ListView) findViewById(R.id.lv);
//解析
jiexi();
//实力化BaseAdapter
my = new MyBaseAdapter(this);
//点击事件
get.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//适配器
lv.setAdapter(my);
}
});
}
//解析的方法
public void jiexi(){
//获取OkOKHttpUitls的工具类
OKHttpUitls okHttpUitls = new OKHttpUitls();
//调用方法
okHttpUitls.get(url);
//接口传至的方法
okHttpUitls.setOnOKHttpGetListener(new OKHttpUitls.OKHttpGetListener() {
@Override
public void error(String error) {//失败
Toast.makeText(MainActivity.this,error,Toast.LENGTH_SHORT).show();
}
@Override
public void success(String json) {//成功
Toast.makeText(MainActivity.this,json,Toast.LENGTH_SHORT).show();
Gson g=new Gson();
Bean bean = g.fromJson(json, Bean.class);
List<Bean.ResultBean.FutureBean> future = bean.getResult().getFuture();
list.addAll(future);
my.notifyDataSetChanged();
}
});
}
class MyBaseAdapter extends BaseAdapter{
private final Context context;
public MyBaseAdapter(Context context) {
this.context = context;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView textView = new TextView(context);
textView.setText(list.get(position).getDate());
return textView;
}
}
}