常用网络框架的使用
Volley框架:
Google官方框架。使用:
在项目的 build.gradle 中, dependencies -- 添加依赖 --> compile 'com.mcxiaoke.volley:library:1.0.19'
然后在 Activity 中代码如下:
//第一步:在主线程中创建队列 RequestQueue requestQueue = Volley.newRequestQueue(this); //第二步:创建一个StringRequest对象 StringRequest request = new StringRequest(...); //第三步:添加到队列,开始执行 requestQueue.add(request);
重点在于:第二步,请求 StringRequest 对象。
发起 HTTP 请求,一般分为两种: Get 请求、Post 请求。
在 StringRequest 中发起 Get 请求,代码如下:
//网址 public static final String path = "http://route.showapi.com/281-2/"; //appId public static final String appid = "15784"; //sign密钥 public static final String sign = "ea5b4bf2e5z3x140498bb772d1bf2a51a7a0"; //Get 请求,直接拼接,所有的 URL 信息都可见,安全性低 private void get() { StringRequest request = new StringRequest(path + "?showapi_appid=" + appid + "&showapi_sign=" + sign, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.e("TAG", "response:" + response); //拿到了结果,可以开始解析,并且显示在界面上 try {
// 在这里解析你所需要的所有 Json 数据 --> Response()方法 parserJson(response); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("TAG", "------------请求出错"); } }); }
在 StringRequest 中发起 Post 请求,代码如下:
//区别在于,第一个参数为 POST 请求 StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.e("TAG", "-----------" + response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("TAG", "-----------" + error.getMessage()); } }) { //需要重写getParams()方法,将参数传入map中 @Override protected Map<String, String> getParams() throws AuthFailureError { HashMap<String, String> map = new HashMap<>(); map.put("showapi_appid", appid); map.put("showapi_sign", sign); String str = et.getText().toString(); if (!str.equals("")) { map.put("textproducer_char_string", str); } return map; } };
XUtils框架:
使用方法:
在项目的 build.gradle 中, dependencies -- 添加依赖 --> compile 'org.xutils:xutils:3.5.0'
代码如下:
//首先你需要在 Application 中初始化 xutils 框架 public class MyApp extends Application { @Override public void onCreate() { super.onCreate(); x.Ext.init(this); } }
然后在 AndroidManifest 中添加 Application
<applicaion
android:name=".MyApp" >
</application>
最后在 Activity 最后代码如下:
// Get 请求:
//请求的参数 RequestParams params = new RequestParams("http://sw.bos.baidu.com/sw-search-sp/software/d59738042c504/mysql-5.7.17.msi"); //打开SD卡,创建一个文件夹 File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/new/aa.msi"); //创建父文件夹路径 file.getParentFile().mkdirs(); //设置文件保存路径 params.setSaveFilePath(file.getAbsolutePath()); //设置是否自动命名 params.setAutoRename(true); //设置最大重试次数 params.setMaxRetryCount(100); //设置是否自动恢复 params.setAutoResume(true); //重点方法。x.http().get() 发起请求 x.http().get(params, new Callback.ProgressCallback<File>() { @Override public void onSuccess(File result) { Log.e("TAG","---------onSuccess"); } @Override public void onError(Throwable ex, boolean isOnCallback) { Log.e("TAG", "----------" + ex.getMessage()); } @Override public void onCancelled(CancelledException cex) { Log.e("TAG","---------onCancelled"); } @Override public void onFinished() { Log.e("TAG","---------onFinished"); } @Override public void onWaiting() { Log.e("TAG","---------onWaiting"); } @Override public void onStarted() { Log.e("TAG","---------onStarted"); } @Override public void onLoading(long total, long current, boolean isDownloading) { Log.e("TAG", "--------------" + total + " " + current); } });
// Post 请求:
RequestParams params = new RequestParams("http://route.showapi.com/341-2"); //添加 appid、sign params.addBodyParameter("showapi_appid", "13074"); params.addBodyParameter("showapi_sign", "ea5b4bf2e140498bb772d1bf2a51a7a0"); //传递json字段 params.setAsJsonContent(true); params.setBodyContent("{json}"); x.http().post(params, new Callback.CommonCallback<String>() { @Override public void onSuccess(String result) { //请求成功 Log.e("TAG", "---------" + result); } @Override public void onError(Throwable ex, boolean isOnCallback) { //请求失败 } @Override public void onCancelled(CancelledException cex) { //被取消 } @Override public void onFinished() { //请求完成 } }); ImageView iv = (ImageView) findViewById(R.id.iv);
//网络框架 加载图片 ImageOptions options = new ImageOptions.Builder().setCrop(true).build(); x.image().bind(iv,"https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png",options);
OkHttp3框架:
使用方法:
在项目的 build.gradle 中, dependencies -- 添加依赖 --> 'com.squareup.okhttp3:okhttp:3.8.1'
代码如下:
// post public void post(){ OkHttpClient httpClient = new OkHttpClient(); RequestBody body = new FormBody.Builder().add("showapi_appid", "41381").add("showapi_sign", "d458e1e057774a0b96a54d9ce06cea5a").build(); Request request = new Request.Builder().url("http://route.showapi.com/341-2").post(body).build(); okhttp3.Call call = httpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { } }); } // get public void get(){ OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url("\"http://route.showapi.com/341-2?showapi_appid=13074&showapi_sign=ea5b4bf2e140498bb772d1bf2a51a7a0").build(); Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { } }); }