构建一个发送请求类:
- /**
- *在调用该方法时,也需构建一个Map对象
- *
- */
- public static boolean sendGetRequest(String path, Map<String, String> params, String enc) throws Exception{
- StringBuilder sb = new StringBuilder(path);
- sb.append('?');
- // ?method=save&title=435435435&timelength=89&
- //把Map中的数据迭代附加到StringBuilder中
- for(Map.Entry<String, String> entry : params.entrySet()){
- //URLEncoder.encode对字符串中文进行编码,防止乱码
- sb.append(entry.getKey()).append('=')
- .append(URLEncoder.encode(entry.getValue(), enc)).append('&');
- }
- //去掉最后一个字符&
- sb.deleteCharAt(sb.length()-1);
- //把组拼完的路径传到URL对象
- URL url = new URL(sb.toString());
- HttpURLConnection conn = (HttpURLConnection)url.openConnection();
- //设置请求方式,GET要大写
- conn.setRequestMethod("GET");
- conn.setConnectTimeout(5 * 1000);
- //"200"代表请求成功
- if(conn.getResponseCode()==200){
- return true;
- }
- return false;
- }
onClick 事件触发:
- public void onClick(View v) {
- //获取标题
- String title = titleText.getText().toString();
- //获取时间长度
- String timelength = timelengthText.getText().toString();
- //通过Map构造器传参
- Map<String, String> params = new HashMap<String, String>();
- params.put("method", "save");
- //为key赋值
- params.put("title", title);
- //为key赋值
- params.put("timelength", timelength);
- try {
- //此处第三个参数,为指定上传数据编码
- HttpRequest.sendGetRequest("http://192.168.1.100:8080/videoweb/video/manage.do", params, "UTF-8");
- //提示成功
- Toast.makeText(MainActivity.this, R.string.success, 1).show();
- } catch (Exception e) {
- //提示失败
- Toast.makeText(MainActivity.this, R.string.error, 1).show();
- Log.e(TAG, e.toString());
- }
- }
测试代码:
- VideoForm formbean = (VideoForm)form;
- if("GET".equals(request.getMethod())){
- //得到原始数据的二进制数据
- byte[] data = request.getParameter("title").getBytes("ISO-8859-1");
- //把二进制数据传给构造器,重新编码为"UTF-8",这样就解决了服务端造成乱码的原因
- String title = new String(data, "UTF-8");
- System.out.println("title:"+ title);
- System.out.println("timelength:"+ formbean.getTimelength());
- }else{
- System.out.println("title:"+ formbean.getTitle());
- System.out.println("timelength:"+ formbean.getTimelength());
- }
如果上传的数据包含中文时可能会出现乱码,主要原因有两个:
①客户端发送请求时没有对URL进行编码,我们只要使用URLEncoder.encode(keyValue,"UTF-8")处理即可。
②Tomcat服务器在获取参数时,默认编码不是"UTF-8",一般是"ISO-8859-1",此时要如何处理呢?
主要思路是这样的:先把以"ISO-8859-1"(假设是这种编码,如果不是也无所谓)编码获取的数据转为最原始的二进码数据,然后再对该二进制数据以"UTF-8"格式进行重新编码,参考上面代码中的实现应该不难理解。