产品提出需求,需要再视频播放完毕后把当前的播放位置上传给服务器。作为一名不爱造轮子的程序员,我果断的使用了三方的视屏播放器,以module依赖的形式导入到了工程,也由此产生了一个问题,三方module没有Application的,也就无法进行集成OkGo来进行简单的网络请求了。这里插入一句,在主module里通过调用辅助module的方法来给三方实现okGo的初始化为什么不可以呢?
回归正题,于是我就在三方的视频回退操作中用原生的网络请求了,代码如下(原生的网络请求必须开启子线程):
new Thread(new Runnable() { @Override public void run() { //自己写一个HttpUrlConnection发起网络请求 String urlPath = new String("http://47.104.108.249:8081/api/edu/mmtb/app/res/multi_media_record/"); JSONObject jsonObject=new JSONObject(); try { jsonObject.put("resMultiMediaId",1); jsonObject.put("record","10000"); } catch (JSONException e) { e.printStackTrace(); } //建立连接f URL url = null; try { url = new URL(urlPath); } catch (MalformedURLException e) { e.printStackTrace(); } HttpURLConnection httpConn = null; try { httpConn = (HttpURLConnection) url.openConnection(); } catch (IOException e) { e.printStackTrace(); } //设置连接超时,2000ms httpConn.setConnectTimeout(2000); //设置指定时间内服务器没有返回数据的超时,5000ms httpConn.setReadTimeout(5000); //设置参数 httpConn.setDoOutput(true); //需要输出 httpConn.setDoInput(true); //需要输入 httpConn.setUseCaches(false); //不允许缓存 try { httpConn.setRequestMethod("POST"); //设置POST方式连接 } catch (ProtocolException e) { e.printStackTrace(); } //设置请求属性,给请求头添加东西 httpConn.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); httpConn.setRequestProperty("accept", "application/json"); httpConn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接 httpConn.setRequestProperty("Charset", "UTF-8"); httpConn.setRequestProperty("token", "VjJaMzQxcE9ENjkJMDAwMDYJOHhkTAloZWp1bi5lZHUuYXBwMTUyNDc5NzEwNQ=="); //建立输入流,向指向的URL传入参数 DataOutputStream dos = null; try { dos = new DataOutputStream(httpConn.getOutputStream()); } catch (IOException e) { e.printStackTrace(); } try { dos.writeBytes(String.valueOf(jsonObject)); } catch (IOException e) { e.printStackTrace(); } try { dos.flush(); } catch (IOException e) { e.printStackTrace(); } try { dos.close(); } catch (IOException e) { e.printStackTrace(); } //获得响应状态 //获得响应状态 int resultCode = 0; try { resultCode = httpConn.getResponseCode(); } catch (IOException e) { e.printStackTrace(); } if (HttpURLConnection.HTTP_OK == resultCode) { StringBuffer sb = new StringBuffer(); String readLine = new String(); BufferedReader responseReader = null; try { responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8")); } catch (IOException e) { e.printStackTrace(); } try { while ((readLine = responseReader.readLine()) != null) { sb.append(readLine).append("\n"); } } catch (IOException e) { e.printStackTrace(); } try { responseReader.close(); } catch (IOException e) { e.printStackTrace(); } Log.i("zhangjiaren", sb.toString()); } } }).start();
因为后台需要以json的形式来上传数据,幸好我经常用JsonObject和JsonArray,拼一个传过去就可以了。当然,前提是已经成功的链接上了服务器,再把拼接好的json字符串通过io流的方式传输过去,并且以字节流的形式,即二进制,很明显,这样是为了保证数据不会解析错误。以上就是“Android使用HttpUrlConnection来实现网络请求”了。
最后说一句,后来题主灵机一动,想想EventBus是在线程间进行操作的,两个module的主线程应该是一样的,为何不试试呢?于是果然不出所料,EventBus也是可以的。代码如下:
VideoEvents videoEvents = new VideoEvents().setType(VideoEvents.VE_SURFACEHOLDER_FINISH_FULLSCREEN); videoEvents.duration=currentPosition; videoEvents.obj = CURRENT_STATE; EventBus.getDefault().post(videoEvents);
上面的是发送消息的,下面的是接收数据后的处理:
public void onEventMainThread(VideoEvents videoEvents) { if (videoEvents.type == VideoEvents.VE_SURFACEHOLDER_FINISH_FULLSCREEN) { Log.i("zhangjiaren","wa,amazing"); String position=String.valueOf(videoEvents.duration); Map<String, String> map = new HashMap<>(); map.put("resMultiMediaId","1"); map.put("record",position); JSONObject jsonObject=new JSONObject(map); OkGo.<String>post(Constants.POST_MEDIA_POINT) .headers("token", SPUtil.DEFAULT.getString("token","")) .upJson(jsonObject) .execute(new com.lzy.okgo.callback.StringCallback() { @Override public void onSuccess(Response<String> response) { //拉取书本信息成功,进行数据绑定 Log.i("zhangjiaren",response.body()); if (200==response.code()){ try { // parserData(response.body()); } catch (Exception e) { e.printStackTrace(); } } } @Override public void onError(Response<String> response) { Log.i("zhangjiaren","拉取书本信息请求出错了"); } }); } }ok,写一下,两年后又需要用到HttpUrlConnection时候,可以15分钟搞定了。