[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);
            }
        }
    }
}

 

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