1.GitHub地址
https://github.com/square/okhttp
2.使用步骤
将下载的包导入
对包进行设置依赖:
最终的效果图:
3.源码
1 public class MainActivity extends AppCompatActivity implements View.OnClickListener{ 2 3 private Button mButtonGetY; 4 private Button mButtonGetA; 5 private Button post; 6 private Button fileDownload,fengzhuang; 7 private TextView mTextView; 8 private String result; 9 10 private OkHttpClient client; 11 private Request mRequest; 12 13 14 /* 15 *直接设置连接超时,初始化OkHttpClient 16 */ 17 private void init(){ 18 client = new OkHttpClient(); 19 client.newBuilder().connectTimeout(10,TimeUnit.SECONDS);//连接超时 20 client.newBuilder().readTimeout(10,TimeUnit.SECONDS);//读取超时 21 client.newBuilder().writeTimeout(10,TimeUnit.SECONDS);//写入超时 22 } 23 /* 24 *事件监听 25 */ 26 private void initListener(){ 27 mButtonGetA.setOnClickListener(this); 28 mButtonGetY.setOnClickListener(this); 29 post.setOnClickListener(this); 30 fileDownload.setOnClickListener(this); 31 } 32 33 /* 34 *初始化布局控件 35 */ 36 private void initialize(){ 37 mButtonGetA=(Button)findViewById(R.id.RequestA); 38 mButtonGetY=(Button)findViewById(R.id.RequestY); 39 post=(Button)findViewById(R.id.fromRequest); 40 fileDownload=(Button)findViewById(R.id.fileDownLoad); 41 mTextView=(TextView)findViewById(R.id.shortcut); 42 } 43 44 45 @Override 46 protected void onCreate(Bundle savedInstanceState){ 47 super.onCreate(savedInstanceState); 48 setContentView(R.layout.activity_main); 49 init(); 50 initialize(); 51 initListener(); 52 } 53 54 55 @Override 56 public void onClick(Viewv){ 57 58 switch(v.getId()){ 59 caseR.id.RequestA: 60 initAsyncGet(); 61 break; 62 caseR.id.RequestY: 63 initSyncData(); 64 break; 65 caseR.id.fromRequest: 66 initPost(); 67 break; 68 caseR.id.fileDownLoad: 69 downLoadFile(); 70 break; 71 } 72 } 73 74 /* 75 *get请求同步方法 76 */ 77 private void initSyncData(){ 78 newThread(newRunnable(){ 79 @Override 80 public void run(){ 81 try{ 82 mRequest = new Request.Builder().url("http://www.baidu.com").build(); 83 Response response = client.newCall(mRequest).execute(); 84 result=response.body().string(); 85 runOnUiThread(new Runnable(){ 86 @Override 87 public void run(){ 88 mTextView.setText(result); 89 Log.d("MainActivity","hello"); 90 } 91 }); 92 } 93 catch(Exceptione){ 94 e.printStackTrace(); 95 } 96 } 97 }).start(); 98 } 99 100 101 /* 102 *异步请求 103 */ 104 private void initAsyncGet(){ 105 new Thread (new Runnable(){ 106 @Override 107 public void run(){ 108 mRequest=newRequest.Builder().url("http://www.baidu.com").build(); 109 client.newCall(mRequest).enqueue(newCallback(){ 110 /** 111 *Acallisarequestthathasbeenpreparedforexecution.Acallcanbecanceled.Asthisobject 112 *representsasinglerequest/responsepair(stream),itcannotbeexecutedtwice. 113 * 114 * 115 *@paramcall是一个接口,是一个准备好的可以执行的request 116 *可以取消,对位一个请求对象,只能单个请求 117 *@parame 118 */ 119 @Override 120 public void onFailure(Callcall,IOExceptione){ 121 Log.d("MainActivity","异步请求失败"); 122 } 123 124 /** 125 * 126 *@paramcall 127 *@paramresponse是一个响应请求 128 *@throwsIOException 129 */ 130 @Override 131 public void onResponse (Call call,final Response response) throws IOException{ 132 /** 133 *通过拿到response这个响应请求,然后通过body().string(),拿到请求到的数据 134 *这里最好用string()而不要用toString() 135 *toString()每个类都有的,是把对象转换为字符串 136 *string()是把流转为字符串 137 */ 138 result=response.body().string(); 139 runOnUiThread(newRunnable(){ 140 @Override 141 publicvoidrun(){ 142 mTextView.setText(result); 143 } 144 }); 145 } 146 }); 147 } 148 }).start(); 149 } 150 151 /* 152 *表单提交 153 */ 154 private void initPost(){ 155 156 String url="http://112.124.22.238:8081/course_api/banner/query"; 157 158 FormBody formBody = new FormBody.Builder() 159 .add("type","1") 160 .build(); 161 mRequest=newRequest.Builder().url(url) 162 .post(formBody).build(); 163 new Thread(new Runnable(){ 164 @Override 165 public void run(){ 166 client.newCall(mRequest).enqueue(newCallback(){ 167 @Override 168 public void onFailure(Call call,IOException e){ 169 Log.d("MainActivity","表单请求失败"); 170 } 171 172 @Override 173 public void onResponse(Call call,Response response)throwsIOException{ 174 runOnUiThread(new Runnable(){ 175 @Override 176 public void run(){ 177 mTextView.setText("提交成功"); 178 } 179 }); 180 } 181 }); 182 } 183 }).start(); 184 } 185 186 187 /* 188 *文件下载地址 189 */ 190 private void downLoadFile(){ 191 192 String url="http://ww2.sinaimg.cn/large/797ccd21gw1fa96zpf7ooj20dw0jtdh7.jpg"; 193 mRequest = newRequest.Builder().url(url).build(); 194 195 new Thread (new Runnable(){ 196 @Override 197 public void run(){ 198 199 client.newCall(mRequest).enqueue(newCallback(){ 200 @Override 201 public void onFailure(Callcall,IOExceptione){ 202 Log.d("MainActivity","下载失败"); 203 } 204 205 @Override 206 public void onResponse(Call call,Response response) throws IOException{ 207 208 //把请求成功的response转换为字节流 209 InputStream inputStream=response.body().byteStream(); 210 /** 211 *在这里要加上权限在mainfests文件中 212 *<uses-permissionandroid:name="android.permission.INTERNET"/> 213 *<uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 214 */ 215 216 FileOutputStream fileOutputStream = new FileOutputStream(new File("/sdcard/girl.jpg")); 217 ///定义一个字节流数组 218 byte[] buffer = new byte[1024]; 219 int len = 0; 220 while((len=inputStream.read(buffer))!=-1){ 221 fileOutputStream.write(buffer,0,len); 222 } 223 //关闭输出流 224 fileOutputStream.flush(); 225 inputStream.close(); 226 Log.d("MainActivity","文件下载成功!"); 227 } 228 }); 229 } 230 }).start(); 231 232 } 233 234 235 236 237 238 }