UrlConnection发送http请求 中文乱码解决
中文乱码
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请求 中文乱码解决的更多相关文章
- 使用httpclient post请求中文乱码解决办法
使用httpclient post请求中文乱码解决办法 在使用httpclient发送post请求的时候,接收端中文乱码问题解决. 正文: 我们都知道,一般情况下使用post请求是不会出现中文乱码 ...
- httpclient post请求中文乱码解决办法
在使用httpclient发送post请求的时候,接收端中文乱码问题解决. 正文: 我们都知道,一般情况下使用post请求是不会出现中文乱码的.可是在使用httpclient发送post请求报文含中文 ...
- Java -- 通过 URLConnection 进行http请求中文乱码
对writer和reader指定字符集 out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "utf-8 ...
- 尚硅谷面试第一季-09SpringMVC中如何解决POST请求中文乱码问题GET的又如何处理呢
目录结构: 关键代码: web.xml <filter> <filter-name>CharacterEncodingFilter</filter-name> &l ...
- get请求与post请求中文乱码问题的解决办法
首先出现中文乱码的原因是tomcat默认的编码方式是"ISO-8859-1",这种编码方式以单个字节作为一个字符,而汉字是以两个字节表示一个字符的. 一,get请求参数中文乱码的解 ...
- 解决Post请求中文乱码问题
解决Post请求中文乱码问题 req.setChracterEncoding()要在获取请求参数前调用才有效,不然还是乱码
- 关于java代码提交HTTP POST请求中文乱码的解决方法
首先说明下这些只是根据我工作常用经验的总结,可能不一定完全对,也不一定全面,但却是最通用的. JAVA里HTTP提交方式 httpurlconnection:jdk里自带的 httpclient:ap ...
- java中文乱码解决之道(七)-----JSP页面编码过程
我们知道JSP页面是需要转换为servlet的,在转换过程中肯定是要进行编码的.在JSP转换为servlet过程中下面一段代码起到至关重要的作用. <%@ page language=" ...
- php mysql 中文乱码解决方法
本文章向码农们介绍php mysql 中文乱码解决方法,对码农们非常实用,需要的码农可以参考一下. 从MySQL 4.1开始引入多语言的支持,但是用PHP插入的中文会出现乱码.无论用什么编码也不行 解 ...
随机推荐
- 前端每日实战:158# 视频演示如何用纯 CSS 创作一个雨伞 toggle 控件
效果预览 按下右侧的"点击预览"按钮可以在当前页面预览,点击链接可以全屏预览. https://codepen.io/comehope/pen/pxLbjv 可交互视频 此视频是可 ...
- 谈谈对AQS的一些理解
AQS的概念 AQS全称AbstractQueuedSynchronizer,是java并发包中的核心类,诸如ReentrantLock,CountDownLatch等工具内部都使用了AQS去维护锁的 ...
- 【GDOI2013模拟4】贴瓷砖
题目 A镇的主街是由N个小写字母构成,镇长准备在上面贴瓷砖,瓷砖一共有M种,第i种上面有Li个小写字母,瓷砖不能旋转也不能被分割开来,瓷砖只能贴在跟它身上的字母完全一样的地方,允许瓷砖重叠,并且同一种 ...
- Scala传递参数遇到的坑
1.方法中的参数全为val型. 例: def insertMap(map:=>Map[String,Int]):Unit={ map+=("b"->2) //报错 ...
- 【shell】文本按行逆序
1.最简单的方法是使用tac [root ~]$ seq |tac 2.使用tr和awk. tr把换行符替换成自定义的分隔符,awk分解替换后的字符串,并逆序输出 [root ~]$ seq | tr ...
- Python 变量类型Ⅲ
Python 元组 元组是另一个数据类型,类似于 List(列表). 元组用 () 标识.内部元素用逗号隔开.但是元组不能二次赋值,相当于只读列表. 以上实例输出结果: 以下是元组无效的,因为元组是不 ...
- .NET DotnetSpider--WebDrvierSpider(ajax动态加载的数据获取)
爬虫获取数据时,可能会遇到AJAX加载的页面,如果无法分析出接口的话,就只能使用秘密武器——WebDriverDownloader.不过最好还是分析出接口为好,WebDriver的性能实在是太低了.现 ...
- 【深入理解CLR】1:CLR的执行模型
将源代码编译成托管模块 下图展示了编译源代码文件的过程.如图所示,可用支持 CLR 的任何一种语言创建源代码文件.然后,用一个对应的编译器检查语法和分析源代码.无论选用哪一个编译器,结果都是一个托管模 ...
- 序列式容器————array
目录 介绍 1 构造函数 2 fill() 3 元素的获取 4 size() 5 empty() 6 front() 7 back() 8 get<n> 9 迭代器(待补充) 10 元素的 ...
- 一款新的好用的SSH工具——FinalShell,比XShell更牛逼~
FinalShell是一体化的的服务器,网络管理软件,不仅是ssh客户端,还是功能强大的开发,运维工具,充分满足开发,运维需求.特色功能:免费海外服务器远程桌面加速,ssh加速,双边tcp加速,内网穿 ...