[Android][网络请求][okhttp] okhttp实现网络请求

okhttp实现网络请求

 

package com.szyh.db.myapplication.http;

import android.util.Log;
import java.io.IOException;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class SemanticsHelper {

    private static final String TAG = "SemanticsHelper";

    private static SemanticsHelper semanticsHelper = new SemanticsHelper();

    private SemanticsHelper() {
    }

    public static SemanticsHelper get() {
        return semanticsHelper;
    }

    /**
     * 请求语义
     * @param result
     */
    public void sendMsg(final String result) {
        String url = "http://192.168.10.181:8808/message";
        RequestBody body = new FormBody.Builder()
                .add("msg", result)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        OkHttpClient okHttpClient = new OkHttpClient();
        final okhttp3.Call call = okHttpClient.newCall(request);
        ThreadManager.getNormalPool().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    okhttp3.Response response = call.execute();
                    String responseResult = response.body().string().replaceAll("\\n|\\s*", "");
                    Log.d(TAG, responseResult);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

}
package com.szyh.lottery.util;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


public class ThreadManager {

    private static ThreadPoolProxy mNormalPool   = new ThreadPoolProxy(3, 5, 5 * 1000);
    private static ThreadPoolProxy mDownloadPool = new ThreadPoolProxy(3, 3, 5 * 1000);

    public static ThreadPoolProxy getNormalPool() {
        return mNormalPool;
    }

    public static ThreadPoolProxy getDownloadPool() {
        return mDownloadPool;
    }


    public static class ThreadPoolProxy {
        private final int                mCorePoolSize;
        private final int                mMaximumPoolSize;
        private final long               mKeepAliveTime;
        private ThreadPoolExecutor mPool;


        public ThreadPoolProxy(int corePoolSize, int maximumPoolSize, long keepAliveTime) {
            this.mCorePoolSize = corePoolSize;
            this.mMaximumPoolSize = maximumPoolSize;
            this.mKeepAliveTime = keepAliveTime;
            Executors.newSingleThreadExecutor();
        }

        private void initPool() {
            if (mPool == null || mPool.isShutdown()) {
                //                int corePoolSize = 1;//核心线程池大小
                //                int maximumPoolSize = 3;//最大线程池大小
                //                long keepAliveTime = 5 * 1000;//保持存活的时间
                TimeUnit unit      = TimeUnit.MILLISECONDS;//单位
                BlockingQueue<Runnable> workQueue = null;//阻塞队列

                workQueue = new ArrayBlockingQueue<Runnable>(3);//FIFO,大小有限制
                //                workQueue = new LinkedBlockingQueue();//
                //                workQueue = new PriorityBlockingQueue();

                ThreadFactory threadFactory = Executors.defaultThreadFactory();//线程工厂

                RejectedExecutionHandler handler = null;//异常捕获器

                //                                handler = new ThreadPoolExecutor.DiscardOldestPolicy();//插队效果,去掉队列中首个任务,将新加入的放到队列中去
                //                                handler = new ThreadPoolExecutor.AbortPolicy();//触发异常
                handler = new ThreadPoolExecutor.DiscardPolicy();//不做任何处理
                //                handler = new ThreadPoolExecutor.CallerRunsPolicy();//直接执行,不归线程池控制,在调用线程中执行

                //                new Thread(task).start();

                mPool = new ThreadPoolExecutor(mCorePoolSize,
                                               mMaximumPoolSize,
                                               mKeepAliveTime,
                                               unit,
                                               workQueue,
                                               threadFactory,
                                               handler);
            }
        }

        /**
         * 执行任务
         * @param task
         */
        public void execute(Runnable task) {
            initPool();

            //执行任务
            mPool.execute(task);
        }


        public Future<?> submit(Runnable task) {
            initPool();
            return mPool.submit(task);
        }

        public void remove(Runnable task) {
            if (mPool != null && !mPool.isShutdown()) {
                mPool.getQueue()
                     .remove(task);
            }
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章