首页 > 代码库 > okhttp使用
okhttp使用
okhttp是一种新的网络请求框架,对网络强求做了优化。
同步调用:
public static String getStringByUrl(String url){ try { initClient(); Request request = new Request.Builder() .url(url) .build(); Response response = client.newCall(request).execute(); String result = response.body().string(); return result; } catch (IOException e) { e.printStackTrace(); return null; } }
private void okhttpTest(){ new Thread(new Runnable() { @Override public void run() { final String url = "http://www.baidu.com"; final String result = OkhttpUtils.getStringByUrl(url); new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show(); } }); } }).start(); }
异步调用:
private void okhttpTest3(final Context context){ final String url = "https://www.baidu.com"; Request request = new Request.Builder() .url(url) .build(); OkHttpClient client = new OkHttpClient(); Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { Toast.makeText(context, "Fail!", Toast.LENGTH_SHORT).show(); } }); } @Override public void onResponse(Response response) throws IOException { final String result = response.body().string(); new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { Toast.makeText(context, result, Toast.LENGTH_SHORT).show(); } }); } }); }
okhttp使用
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。