安卓httprul post方式上传中文乱码问题解决方案

来源:互联网 发布:知乎怎么删除文章 编辑:程序博客网 时间:2024/05/01 00:08

    在使用httpurl post方式和服务器端jsp进行交互时,出现了写入中文乱码问题,且此时jdbc没有问题,服务器端MySQL已配置好utf-8码制。此时可以确定问题是本地代码中post请求写入变量代码存在问题。给出代码作为案例:

public void send() {  //获取数据String target = "服务器端jsp地址"; // 要提交的目标地址URL url;try {url = new URL(target);HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); // 创建一个HTTP连接urlConn.setRequestMethod("POST"); // 指定使用POST请求方式urlConn.setDoInput(true); // 向连接中写入数据urlConn.setDoOutput(true); // 从连接中读取数据urlConn.setUseCaches(false); // 禁止缓存urlConn.setInstanceFollowRedirects(true); // 自动执行HTTP重定向urlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); // 设置内容类型DataOutputStream out = new DataOutputStream(urlConn.getOutputStream()); // 获取输出流String sql="SELECT  *  FROM  course " + " where coursecademy='"+ ac +"'and  coursedepartment='"+de+"' "+"and coursename not in(select courseid from chooseinfo where userid='"+user+"');";//传入学院  专业  和学生idLog.e("此处", ac);Log.e("此处", de);String param = "sql=" + URLEncoder.encode(sql, "utf-8"); // 连接所要提交的数据out.writeBytes(param);// 将要传递的数据写入数据输出流out.flush(); // 输出缓存out.close(); // 关闭数据输出流// 判断是否响应成功if (urlConn.getResponseCode() == HttpURLConnection.HTTP_OK) {InputStreamReader in = new InputStreamReader(urlConn.getInputStream()); // 获得读取的内容BufferedReader buffer = new BufferedReader(in); // 获取输入流对象String inputLine = null;strres = "";while ((inputLine = buffer.readLine()) != null) {strres += inputLine ;}in.close(); // 关闭字符输入流}urlConn.disconnect(); // 断开连接} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}
    以上为一个使用httpurl post方式进行信息发送的代码,有详细注释,很容易看懂。

注意传入的sql变量已经进行了utf-8编码,此时传入英文没有问题,但传入中文会出现乱码。

    解决方法:将urlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");改为: urlConn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded; charset=utf-8");  即可。


0 0
原创粉丝点击