第二阶段冲刺二
今天主要完成的任务:OKHttp3框架的学习和应用
遇到的困难:不懂上传文件的原理也不知道改如何上传
解决办法:补充计网的一些知识,参考http传送数据的博客
今日体会:自己一定要学会使用优秀的开源框架,学会阅读github上的文档说明,只有这样,自己才能更好的将框架封装成自己想要的功能,比如说OKHttp3框架
源程序代码
同步GET请求
String url = "http://wwww.baidu.com"; OkHttpClient okHttpClient = new OkHttpClient(); final Request request = new Request.Builder() .url(url) .build(); final Call call = okHttpClient.newCall(request); new Thread(new Runnable() { @Override public void run() { try { Response response = call.execute(); Log.d(TAG, "run: " + response.body().string()); } catch (IOException e) { e.printStackTrace(); } } }).start();
POST方式提交String
MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8"); String requestBody = "I am Jdqm."; Request request = new Request.Builder() .url("https://api.github.com/markdown/raw") .post(RequestBody.create(mediaType, requestBody)) .build(); OkHttpClient okHttpClient = new OkHttpClient(); okHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.d(TAG, "onFailure: " + e.getMessage()); } @Override public void onResponse(Call call, Response response) throws IOException { Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message()); Headers headers = response.headers(); for (int i = 0; i < headers.size(); i++) { Log.d(TAG, headers.name(i) + ":" + headers.value(i)); } Log.d(TAG, "onResponse: " + response.body().string()); } });