本文主要是介绍UrlConnection post请求中文参数乱码问题,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1、在用UrlConnection进行网络编程,往往出现请求参数出现中文时,中文乱码,需要在请求中指定请求编码格式
public static String sendPost() {
String result = "";BufferedReader in = null;
try {
String IP_AdRESS="http://localhost:8080/studyhelp/loginAServlet";
/*"/GPServer/"+ method +*/
String urlNameString = IP_AdRESS;
URL realUrl = new URL(urlNameString);
URLConnection connection = realUrl.openConnection();
//设置网络请求时间最多为5秒;
connection.setConnectTimeout(5000);
//读取网页请求结果时间为15秒
connection.setReadTimeout(25000);
//设置网络请求时间最多为5秒;
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.setDoOutput(true);
connection.setDoInput(true);
//设置请求编码格式
connection.setRequestProperty("Accept-Charset", "GBK");connection.setRequestProperty("contentType", "GBK");
// 获取URLConnection对象对应的输出流
String dataparam="f=pjson&name=张三";
//文件流编码设置
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "GBK");
out.write(dataparam);
//错误方式,这种方式容易出现乱码
// PrintWriter out = new PrintWriter(connection.getOutputStream());/*out.print(dataparam);*/
// flush输出流的缓冲
out.flush();
in = new BufferedReader(new InputStreamReader(
connection.getInputStream(),"UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
这篇关于UrlConnection post请求中文参数乱码问题的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!