Get方法是在子线程中获取网络数据,而且是同步的;
1.为什么Post方法不是从子线程向服务器推送呢? 2.Response难道也不用从子线程中相应吗? 3.Post和Response都是异步的,异步不用子线程吗? 上课代码如下: private void post() { Request.Builder builder = new Request.Builder(); builder.url(POST_URL); builder.post(RequestBody.create(MEDIA_TYPE_MARKDOWN, "Hello world github/linguist#1 **cool**, and #1!")); Request request = builder.build(); Call call = mClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { final String content = response.body().string(); runOnUiThread(new Runnable() { @Override public void run() { mContentTextView.setText(content); } }); } } }); } private void response() { Request.Builder builder = new Request.Builder(); builder.url("https://raw.githubusercontent.com/square/okhttp/master/README.md"); Request request = builder.build(); Call call = mClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.d(TAG, "onFailure() called with: call = [" + call + "], e = [" + e + "]"); } @Override public void onResponse(Call call, Response response) throws IOException { Log.d(TAG, "onResponse() called with: call = [" + call + "], response = [" + response + "]"); int code = response.code(); Headers headers = response.headers(); String content = response.body().string(); final StringBuilder buf = new StringBuilder(); buf.append("code: " + code); buf.append("\nHeaders: \n" + headers); buf.append("\nbody: \n" + content); runOnUiThread(new Runnable() { @Override public void run() { mContentTextView.setText(buf.toString()); } }); } }); } private void get() { ExecutorService executor = Executors.newSingleThreadExecutor(); executor.submit(new Runnable() { @Override public void run() { Request.Builder builder = new Request.Builder(); builder.url("https://raw.githubusercontent.com/square/okhttp/master/README.md"); Request request = builder.build(); Log.d(TAG, "run: " + request); Call call = mClient.newCall(request); try { Response response = call.execute(); if (response.isSuccessful()) { final String string = response.body().string(); runOnUiThread(new Runnable() { @Override public void run() { mContentTextView.setText(string); } }); } } catch (IOException e) { e.printStackTrace(); } } }); executor.shutdown(); }
0
收起
正在回答 回答被采纳积分+1
1回答
Android网络操作与数据存储2018版
- 参与学习 人
- 提交作业 307 份
- 解答问题 1613 个
本专题是联网及数据处理的必备技能。课程从网络基础知识到线程间协同工作、异步下载处理。介绍了Android内外部文件存储、轻量级数据库SQLite的使用。利用屏幕适配、状态保持、百度地图解决实际问题。
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星