导入
compile 'com.squareup.okhttp3:okhttp:3.3.0'
GET请求
String url = "https://www.baidu.com/"; OkHttpClient okHttpClient = new OkHttpClient(); Request request = new Request.Builder() .url(url) .build(); Call call = okHttpClient.newCall(request); try { Response response = call.execute(); System.out.println(response.body().string()); } catch (IOException e) { e.printStackTrace(); }
POST请求
private void DownloadFile() { OkHttpClient.Builder client = new OkHttpClient.Builder(); //设置超时 client.connectTimeout(20, TimeUnit.SECONDS).writeTimeout(20, TimeUnit.SECONDS).readTimeout(20, TimeUnit.SECONDS).build(); OkhttpUtil.allowAllSSL(client); //传递的参数通过add连接 RequestBody formBody = new FormBody.Builder().add("key1", value1) .add("key2", key2).add("key3", key3).build(); okhttp3.Request request = new okhttp3.Request.Builder().url(downloadString).post(formBody).build(); call = client.build().newCall(request); call.enqueue(new Callback() { //失败的回调 @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); if (m_pDialog.isShowing()) { AlertText("网络连接超时,请检查您的网络连接。"); } } //成功的回调 @Override public void onResponse(Call call, okhttp3.Response response) throws IOException { InputStream is = null; FileOutputStream fos = null; Headers responseHeaders = response.headers(); for (int i = 0; i < responseHeaders.size(); i++) { if (responseHeaders.name(i).equals("Content-Disposition")) { fileName = new String(responseHeaders.value(i)).substring(21, responseHeaders.value(i).length()); } } try { is = response.body().byteStream(); String dir = Environment.getExternalStorageDirectory() + "/sss/"; if (FileUtil.makeFolder(dir)) { File file = new File(dir, fileName); fos = new FileOutputStream(file); byte[] buf = new byte[1024]; int ch = -1; while ((ch = is.read(buf)) != -1) { fos.write(buf, 0, ch); } fos.flush(); if (fos != null) { fos.close(); } OpenFile(); } else { AlertText("程序自动试图创建文件夹失败"); } } catch (Exception e) { e.printStackTrace(); if (m_pDialog.isShowing()) { AlertText("您所下载的内容不存在。"); } } finally { try { if (is != null) is.close(); } catch (IOException e) { e.printStackTrace(); } try { if (fos != null) fos.close(); } catch (IOException e) { e.printStackTrace(); } } } }); }