android客户端向服务端传汉字乱码问题
最近在做android,遇到从android客户端向服务器端发送汉字乱码问题。采用URLConnection的GET方式,在客户端和服
务端都需要进行转码,而采用POST方式则不需要转码。具体方法如下:
用URLConnection从android发送数据有两种方式:
第一种方式:采用get方式传值
(1)客户端代码:
URL url = new URL(mUrl);
URLConnection urlConnection = url.openConnection();
InputStream is = urlConnection.getInputStream();
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = is.read()) != -1) {
baf.append((byte) current);
}
requestInfo = new String(baf.toByteArray(), "UTF-8").trim();
is.close();
对汉字进行处理:
URLEncoder.encode(URLEncoder.encode(channelName, "UTF-8"), "UTF-8")
(2)服务器端接收字段:
URLDecoder.decode(URLDecoder.decode(request.getParameter("nickname"), "UTF-8"), "UTF-8")
第二种方式:采用Post方式:
客户端代码:
public String sendRemoteRequest(String path,String param){
Log.i("lisheng", param.toString());
Log.i("lisheng", path);
String strRes="";
OutputStream os = null;
DataOutputStream dos = null;
InputStream is = null;
BufferedReader br = null;
try {
URL url = new URL(path);
URLConnection urlConn = url.openConnection();
urlConn.setDoInput(true);
urlConn.setDoOutput(true);
os = urlConn.getOutputStream();
dos = new DataOutputStream(os);
dos.write(param.getBytes());
dos.flush();
dos.close();
os.close();
is = urlConn.getInputStream();
br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
for (String strLine = ""; (strLine = br.readLine()) != null;)
strRes = (new StringBuilder(String.valueOf(strRes))).append(strLine).toString();
is.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return strRes;
}
参数里直接写汉字
服务器端代码:
request.setCharacterEncoding("UTF-8");
request.getParameter("nickname")
即可得到参数为汉字的值,不需要转码。
更多相关文章
- android imageView 图片显示方式属性
- Netty多语言(Java、Android(安卓)、C#、WebSocket)通信实例Demo (一
- SSH服务器与Android通信(2)--Android客户端接收数据
- Android之ShortCut[Broadcast方式]
- android 设置主页面的方式
- android中解析文件的三种方式
- android中使用URL Scheme方式启动app
- android客户端控制树莓派GPIO点亮LED灯
- Android(安卓)(SQLite 数据库与ContentProvider)