Android Webview posturl 传参encode问题
1、起因,闲话少说,近期因项目需求,需要在webview必须通过post方式加载url并传参,自然想到posturl(url,byte[])
2、问题,起初很简单,JSON拼接参数,然后转String,最后String.getBytes(),自然得到了byte[],服务器也很顺利接收到了,可是呢顺利的话应该是一个正常的json串,直接解析就能得到数据,服务端接收到的json串被encode了,例如{}、""等都被encode了,本来呢直接decode也可以解决,偏偏IOS端是正常的,想办法。
3、解决问题,途径1:通过httpPost将数据post上去,再接收httpresponse,最后拿到response的数据放到webview去加载,前期post跟接收response轻易解决,但是偏偏在解析response加载到webview的时候又出现问题,试着debug调试,未果,索性研究其他办法。
途径2:还是webview.posturl,区别在于得到json串以后不直接转String,而是通过StringEntity,详情见以下代码StringEntity se = null; try { se = new StringEntity(jsonObject.toString(),"UTF-8"); se.setContentType("application/json"); byte[] array = EntityUtils.toByteArray(se); webView.postUrl(url, array); } catch (Exception e) { e.printStackTrace(); }
途径3:重写 webview 的 shouldInterceptRequest,针对特定请求修改请求头,详见以下代码
@Override public WebResourceResponse shouldInterceptRequest(WebView view, String url) { try { if (url.equals("http://192.168.0.12:8080/tt.php")) { URL url1 = new URL(url); HttpURLConnection conn = (HttpURLConnection) url1.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-type", "application/json"); String data = "{\"name\":\"test\"}"; conn.getOutputStream().write(data.getBytes()); WebResourceResponse resp = new WebResourceResponse("text/html", conn.getHeaderField("encoding"), conn.getInputStream()); return resp; } }catch(Exception e){} return super.shouldInterceptRequest(view, url); }
为了方便测试,在本机搭了个简单的服务器,直接生成一个servlet,修改web.xml映射,保证手机电脑在一个网段,在手机端直接访问电脑ip/projectname/servlet映射名称,例如 192.168.0.123/ServerDemo/myServlet,在servlet的dopost方法中解析就可以看到在安卓端webview通过post传递的参数