OkHttpUtils

来源:互联网 发布:java 字符串转10进制 编辑:程序博客网 时间:2024/05/21 07:13

OkHttpUtils工具类

package com.example.eggplant_doctor.util;import com.squareup.okhttp.Call;import com.squareup.okhttp.FormEncodingBuilder;import com.squareup.okhttp.OkHttpClient;import com.squareup.okhttp.Request;import com.squareup.okhttp.RequestBody;import com.squareup.okhttp.Response;import java.io.IOException;import java.util.Map;/** * Created by Administrator on 2016/6/14. */public class Okutil {    private static OkHttpClient client;    public static String getGet(String url) {//创建okHttpClient对象        OkHttpClient mOkHttpClient = new OkHttpClient();//创建一个Request        final Request request = new Request.Builder()                .url(url)                .build();//new call        Call call = mOkHttpClient.newCall(request);//请求加入调度        try {            Response response = call.execute();            return response.body().string();        } catch (IOException e) {            e.printStackTrace();        }        return null;    }    public static String getGetGbk(String url) {//创建okHttpClient对象        OkHttpClient mOkHttpClient = new OkHttpClient();//创建一个Request        final Request request = new Request.Builder()                .url(url)                .build();//new call        Call call = mOkHttpClient.newCall(request);//请求加入调度        try {            Response response = call.execute();            return new String(response.body().bytes(),"gbk");        } catch (IOException e) {            e.printStackTrace();        }        return null;    }    public static String getPost(String url, Map<String, String> data) throws IOException {        client = new OkHttpClient();        FormEncodingBuilder formBuilder = new FormEncodingBuilder();        for (Map.Entry<String, String> item : data.entrySet()) {            formBuilder.add(item.getKey(), item.getValue());           /* Log.i("key", item.getKey());            Log.i("values", item.getValue());*/        }        RequestBody body = formBuilder.build();        Request request = new Request.Builder().url(url).post(body).build();        Response response = excute(request);        if (response.isSuccessful()) {            return response.body().string();        } else {            throw new IOException("Unexpected code " + response);        }    }    private static Response excute(Request request) throws IOException {        return client.newCall(request).execute();    }}

在类中调用

 new Thread(new Runnable() {            @Override            public void run() {                String get = Okutil.getGet("http://www.hengboit.com/json/CourseInformation.json");                getActivity().runOnUiThread(new Runnable() {                    @Override                    public void run() {                        Gson g=new Gson();                    }                });            }        }).start();
0 0