中文乱码

         DataOutputStream dos = new DataOutputStream(httpConn.getOutputStream());
//dos.writeBytes(jsonData); 这个方法会有中文乱码,使用下面的方法解决
dos.write(jsonData.getBytes("utf-8"));
package com.itstudy;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry; /**
* http 工具封装类
*/
public class HttpURLConnectionUtils { /**
* 发送get请求
*
* @param url
* @param headers
* @return
*/
public static String get(String url, Map<String, String> headers, Map<String, String> params) { String result = "";
try {
if(params!=null) {
StringBuilder sbParams = new StringBuilder();
for (Entry<String, String> entry : params.entrySet()) {
sbParams.append(entry.getKey());
sbParams.append("=");
sbParams.append(entry.getValue());
sbParams.append("&");
} if (sbParams.length() > 0) {
sbParams.deleteCharAt(sbParams.lastIndexOf("&"));
if (url.indexOf("?") > 0) {
url = url + "&" + sbParams.toString();
} else {
url = url + "?" + sbParams.toString();
}
}
} URL restServiceURL = new URL(url);
HttpURLConnection httpConnection = (HttpURLConnection) restServiceURL.openConnection();
httpConnection.setRequestMethod("GET");
httpConnection.setRequestProperty("Charsert", "UTF-8"); //设置请求编码
httpConnection.setRequestProperty("Accept", "*/*"); if (headers != null) {
for (Entry<String, String> entry : headers.entrySet()) {
httpConnection.setRequestProperty(entry.getKey(), entry.getValue().toString());
}
} if (httpConnection.getResponseCode() != 200) {
throw new RuntimeException("HTTP GET Request Failed with Error code : "
+ httpConnection.getResponseCode() + " url:" + url);
} InputStream inputStream = httpConnection.getInputStream();
result = readAll(inputStream);
inputStream.close(); } catch (Exception e) {
e.printStackTrace();
} return result;
} /**
* 发送post form请求
*
* @param url
* @param headers
* @param params
* @return
*/
public static String postForm(String url, Map<String, String> headers, Map<String, String> params) { String result = ""; try {
StringBuilder sbParams = new StringBuilder();
for (Entry<String, String> entry : params.entrySet()) {
sbParams.append(entry.getKey());
sbParams.append("=");
sbParams.append(entry.getValue().toString());
sbParams.append("&");
}
if (sbParams.length() > 0) {
sbParams.deleteCharAt(sbParams.lastIndexOf("&"));
} URL reqUrl = new URL(url);
HttpURLConnection httpConn = (HttpURLConnection) reqUrl.openConnection(); //设置参数
httpConn.setDoOutput(true); //需要输出
httpConn.setDoInput(true); //需要输入
httpConn.setUseCaches(false); //不允许缓存
httpConn.setRequestMethod("POST"); //设置POST方式连接 //设置请求属性
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
httpConn.setRequestProperty("Charset", "UTF-8");
httpConn.setRequestProperty("accept", "*/*"); if (headers != null) {
for (Entry<String, String> entry : headers.entrySet()) {
httpConn.setRequestProperty(entry.getKey(), entry.getValue().toString());
}
} //建立输入流,向指向的URL传入参数
DataOutputStream dos = new DataOutputStream(httpConn.getOutputStream());
//dos.writeBytes(sbParams.toString()); 这个方法会有中文乱码
dos.write(sbParams.toString().getBytes("utf-8")); //解决中文乱码
dos.flush();
dos.close(); if (httpConn.getResponseCode() != 200) {
throw new RuntimeException("HTTP POST form Request Failed with Error code : "
+ httpConn.getResponseCode() + " url:" + url + " form:" + params.toString());
} InputStream inputStream = httpConn.getInputStream();
result = readAll(inputStream);
inputStream.close(); } catch (Exception e) {
e.printStackTrace();
} return result;
} /**
* 发送json请求
*
* @param url
* @param headers
* @param jsonData
* @return
*/
public static String postJSON(String url, Map<String, Object> headers, String jsonData) { String result = ""; try { URL reqUrl = new URL(url);
HttpURLConnection httpConn = (HttpURLConnection) reqUrl.openConnection(); //设置参数
httpConn.setDoOutput(true); //需要输出
httpConn.setDoInput(true); //需要输入
httpConn.setUseCaches(false); //不允许缓存
httpConn.setRequestMethod("POST"); //设置POST方式连接 //设置请求属性
httpConn.setRequestProperty("Content-Type", "application/json");
httpConn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
httpConn.setRequestProperty("Charset", "UTF-8");
httpConn.setRequestProperty("accept", "*/*"); if (headers != null) {
for (Entry<String, Object> entry : headers.entrySet()) {
httpConn.setRequestProperty(entry.getKey(), entry.getValue().toString());
}
} //建立输入流,向指向的URL传入参数
DataOutputStream dos = new DataOutputStream(httpConn.getOutputStream());
//dos.writeBytes(jsonData); 这个方法会有中文乱码,使用下面的方法解决
dos.write(jsonData.getBytes("utf-8"));
dos.flush();
dos.close(); if (httpConn.getResponseCode() != 200) {
throw new RuntimeException("HTTP POST json Request Failed with Error code : "
+ httpConn.getResponseCode() + " url:" + url + " json:" + jsonData);
} InputStream inputStream = httpConn.getInputStream();
result = readAll(inputStream);
inputStream.close(); } catch (Exception e) {
e.printStackTrace();
} return result;
} /**
* 读取字节流
*
* @param inputStream
* @return
*/
private static String readAll(InputStream inputStream) { StringBuilder builder = new StringBuilder(); try {
byte[] b = new byte[1024];
int length = -1;
while ((length = inputStream.read(b)) != -1) {
builder.append(new String(b, 0, length,"UTF-8"));
}
} catch (Exception ex) {
ex.printStackTrace();
}
return builder.toString();
} /**
* formupload方式提交数据
*
* @param urlPath
* @param textMap
* @param fileMap
* @return
*/
public static String formUpload(String urlPath, Map<String, String> textMap, Map<String, String> fileMap) {
String res = "";
HttpURLConnection conn = null;
String BOUNDARY = "----lwm12345boundary"; //boundary就是request头和上传文件内容的分隔符
try {
URL url = new URL(urlPath);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(30000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); OutputStream out = new DataOutputStream(conn.getOutputStream());
// text
if (textMap != null) {
StringBuffer strBuf = new StringBuffer();
Iterator<Entry<String, String>> iter = textMap.entrySet().iterator();
while (iter.hasNext()) {
Entry<String, String> entry = iter.next();
String inputName = (String) entry.getKey();
String inputValue = (String) entry.getValue();
if (inputValue == null) {
continue;
}
strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n");
strBuf.append(inputValue);
}
out.write(strBuf.toString().getBytes("utf-8"));
} // file
if (fileMap != null) {
Iterator<Entry<String, String>> iter = fileMap.entrySet().iterator();
while (iter.hasNext()) {
Entry<String, String> entry = iter.next();
String inputName = (String) entry.getKey();
String inputValue = (String) entry.getValue();
if (inputValue == null) {
continue;
}
File file = new File(inputValue);
String filename = file.getName(); String contentType = MimeTypeUtils.getType(filename); StringBuffer strBuf = new StringBuffer();
strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + filename + "\"\r\n");
strBuf.append("Content-Type:" + contentType + "\r\n\r\n"); out.write(strBuf.toString().getBytes("utf-8")); DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
in.close();
}
} byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
out.write(endData);
out.flush();
out.close(); // 读取返回数据
StringBuffer strBuf = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
strBuf.append(line).append("\n");
}
res = strBuf.toString();
reader.close();
reader = null;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
}
return res;
} /**
* 发送下载文件请求
*
* @param urlPath
* @param downloadDir
* @return
*/
public static File downloadFile(String urlPath, String downloadDir) {
File file = null;
try {
// 统一资源
URL url = new URL(urlPath);
// 连接类的父类,抽象类
URLConnection urlConnection = url.openConnection();
// http的连接类
HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
// 设定请求的方法,默认是GET
httpURLConnection.setRequestMethod("POST");
// 设置字符编码
httpURLConnection.setRequestProperty("Charset", "UTF-8");
// 打开到此 URL 引用的资源的通信链接(如果尚未建立这样的连接)。
httpURLConnection.connect(); // 文件大小
int fileLength = httpURLConnection.getContentLength(); // 文件名
String filePathUrl = httpURLConnection.getURL().getFile();
String fileFullName = filePathUrl.substring(filePathUrl.lastIndexOf(File.separatorChar) + 1); System.out.println("file length---->" + fileLength); URLConnection con = url.openConnection(); BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream()); String path = downloadDir + File.separatorChar + fileFullName;
file = new File(path);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
OutputStream out = new FileOutputStream(file);
int size = 0;
int len = 0;
byte[] buf = new byte[1024];
while ((size = bin.read(buf)) != -1) {
len += size;
out.write(buf, 0, size);
// 打印下载百分比
// System.out.println("下载了-------> " + len * 100 / fileLength +
// "%\n");
}
bin.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
return file;
} } /**
* formupload方式提交转发文件流
*
* @param urlPath
* @param textMap
* @param fileMap
* @return
*/
public static String formUpload2(String urlPath, Map<String, String> textMap, Map<String, InputStream> fileMap) {
String res = "";
HttpURLConnection conn = null;
String BOUNDARY = "----lwm12345boundary"; //boundary就是request头和上传文件内容的分隔符
try {
URL url = new URL(urlPath);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(30000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); OutputStream out = new DataOutputStream(conn.getOutputStream());
// text
if (textMap != null) {
StringBuffer strBuf = new StringBuffer();
Iterator<Entry<String, String>> iter = textMap.entrySet().iterator();
while (iter.hasNext()) {
Entry<String, String> entry = iter.next();
String inputName = (String) entry.getKey();
String inputValue = (String) entry.getValue();
if (inputValue == null) {
continue;
}
strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n");
strBuf.append(inputValue);
}
out.write(strBuf.toString().getBytes("utf-8"));
} // file
if (fileMap != null) {
Iterator<Entry<String, InputStream>> iter = fileMap.entrySet().iterator();
while (iter.hasNext()) {
Entry<String, InputStream> entry = iter.next();
String inputName = (String) entry.getKey();
InputStream fileStream = entry.getValue(); String contentType = MimeTypeUtils.getType(inputName); StringBuffer strBuf = new StringBuffer();
strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + inputName + "\"\r\n");
strBuf.append("Content-Type:" + contentType + "\r\n\r\n"); out.write(strBuf.toString().getBytes("utf-8")); DataInputStream in = new DataInputStream(fileStream);
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
in.close();
}
} byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
out.write(endData);
out.flush();
out.close(); // 读取返回数据
StringBuffer strBuf = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
strBuf.append(line).append("\n");
}
res = strBuf.toString();
reader.close();
reader = null;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
}
return res;
} }

UrlConnection发送http请求 中文乱码解决的更多相关文章

  1. 使用httpclient post请求中文乱码解决办法

    使用httpclient post请求中文乱码解决办法   在使用httpclient发送post请求的时候,接收端中文乱码问题解决. 正文: 我们都知道,一般情况下使用post请求是不会出现中文乱码 ...

  2. httpclient post请求中文乱码解决办法

    在使用httpclient发送post请求的时候,接收端中文乱码问题解决. 正文: 我们都知道,一般情况下使用post请求是不会出现中文乱码的.可是在使用httpclient发送post请求报文含中文 ...

  3. Java -- 通过 URLConnection 进行http请求中文乱码

    对writer和reader指定字符集 out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "utf-8 ...

  4. 尚硅谷面试第一季-09SpringMVC中如何解决POST请求中文乱码问题GET的又如何处理呢

    目录结构: 关键代码: web.xml <filter> <filter-name>CharacterEncodingFilter</filter-name> &l ...

  5. get请求与post请求中文乱码问题的解决办法

    首先出现中文乱码的原因是tomcat默认的编码方式是"ISO-8859-1",这种编码方式以单个字节作为一个字符,而汉字是以两个字节表示一个字符的. 一,get请求参数中文乱码的解 ...

  6. 解决Post请求中文乱码问题

    解决Post请求中文乱码问题 req.setChracterEncoding()要在获取请求参数前调用才有效,不然还是乱码

  7. 关于java代码提交HTTP POST请求中文乱码的解决方法

    首先说明下这些只是根据我工作常用经验的总结,可能不一定完全对,也不一定全面,但却是最通用的. JAVA里HTTP提交方式 httpurlconnection:jdk里自带的 httpclient:ap ...

  8. java中文乱码解决之道(七)-----JSP页面编码过程

    我们知道JSP页面是需要转换为servlet的,在转换过程中肯定是要进行编码的.在JSP转换为servlet过程中下面一段代码起到至关重要的作用. <%@ page language=" ...

  9. php mysql 中文乱码解决方法

    本文章向码农们介绍php mysql 中文乱码解决方法,对码农们非常实用,需要的码农可以参考一下. 从MySQL 4.1开始引入多语言的支持,但是用PHP插入的中文会出现乱码.无论用什么编码也不行 解 ...

随机推荐

  1. 微信小程序中的自定义组件(components)

     其实小程序开发很像vue和react的结合,数据绑定和setData  重新渲染页面的数据,最近发现连写组件都是很像,也是醉了,自我认为哈, 因为小程序可以将页面内的功能模块抽象成自定义组件,以便在 ...

  2. 第二章Python入门

    第二章 Python入门 2.1.简介 Python是著名的"龟叔"(Guido van Rossum)在1989年圣诞节期间,为了打发无聊的圣诞节而编写的一个编程语言 Pytho ...

  3. percona 5.7 + tokudb

    percona 5.7 + tokudb Percona + TokuDB 部署 # 参考资料https://www.kancloud.cn/devops-centos/centos-linux-de ...

  4. 【NOIP2017提高组模拟12.24】B

    题目 现在你有N个数,分别为A1,A2,-,AN,现在有M组询问需要你回答.每个询问将会给你一个L和R(L<=R),保证Max{Ai}-Min{Ai}<=R-L,你需要找出并输出最小的K( ...

  5. 【NOIP2017提高组模拟12.10】神炎皇

    题目 神炎皇乌利亚很喜欢数对,他想找到神奇的数对. 对于一个整数对(a,b),若满足a+b<=n且a+b是ab的因子,则成为神奇的数对.请问这样的数对共有多少呢? 分析 设\(gcd(a,b)= ...

  6. Idea创建多模块依赖Maven项目

    idea 创建多模块依赖Maven项目   本来网上的教程还算多,但是本着自己有的才是自己的原则,还是自己写一份的好,虽然可能自己也不会真的用得着. 1. 创建一个新maven项目 2. 3. 输入g ...

  7. xgboost使用细节

    from http://blog.csdn.net/zc02051126/article/details/46771793 在Python中使用XGBoost 下面将介绍XGBoost的Python模 ...

  8. 虚拟机安装 Output error file to the following location

    有的用户会对你中安装虚拟机系统,但偶尔会在安装过程中遇到一些问题.比如在电脑安装虚拟机系统时出现提示“Output error file to the following location”,这一般是 ...

  9. linux-history-ps1-1

    1.串行端口终端(/dev/ttySn) 串行端口终端(Serial Port Terminal)是使用计算机串行端口连接的终端设备.计算机把每个串行端口都看作是一个字符设备.有段时间这些串行端口设备 ...

  10. C# 获得对象的命名空间 ?.

    A a = new A(); var t = a?.ToString(); //t = WebApplication1.Controllers.A //获得命名空间和类名 var t1 = (A)nu ...