public class okHttp { private String httprequest; private static okHttp mInstance; private OkHttpClient mOkHttpClient; public okHttp() { mOkHttpClient = new OkHttpClient(); //cookie enabled mOkHttpClient.setCookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER)); Handler mDelivery = new Handler(Looper.getMainLooper()); } public static okHttp getInstance() { if (mInstance == null) { synchronized (okHttp.class) { if (mInstance == null) { mInstance = new okHttp(); } } } return mInstance; } /** * 同步的Get请求 * * @param url * @return Response */ private Response _getAsyn(String url) throws IOException { final Request request = new Request.Builder() .url(url) .build(); Call call = mOkHttpClient.newCall(request); Response execute = call.execute(); return execute; } /** * 同步的Get请求 * * @param url * @return 字符串 */ public String _getAsString(String url) { String str=null; Response execute = null; try { execute = _getAsyn(url); } catch (IOException e) { e.printStackTrace(); } try { str= execute.body().string(); } catch (IOException e) { e.printStackTrace(); } return str; } }
<uses-permission android:name="android.permission.INTERNET"/>
//Activity
//请求listview展示数据 private void gethttp(final String s) { new Thread() { @Override public void run() { super.run(); final String str = instance._getAsString(s); final MenuTest menuTest = gson.fromJson(str, MenuTest.class); runOnUiThread(new Runnable() { @Override public void run() { listMenu.add(menuTest); } }); } }.start(); }