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插入的中文会出现乱码.无论用什么编码也不行 解 ...
随机推荐
- 软件安装:树上分组DP/tarjan缩点/(也许基环树?)
提炼:tarjan环缩成点,建0虚根,跑树形DP,最难的是看出可能有n个点n条边然后缩点,n个点n条边可能不只有一个环 n个点n条边->基环树: 基环树,也是环套树,简单地讲就是树上在加一条边. ...
- html头部和底部固定时,中间的内容随屏幕分别率铺满页面
html页面头部和底部有东西时,怎么让内容填充到中间的页面,且去适应不同的电脑分辨率,看代码 <!DOCTYPE html> <html> <head> <m ...
- js对对象增加删除属性
1.首选创建一个对象 var a={}; 2.然后对这个对象赋值 a.name='zhouy';console.log(a);var age="age";a[age]=26;con ...
- shell实现统计浏览次数并将结果保存到文件中
日志文件是每日一个.统计日志文件中的关键字,获取每日浏览次数.将次数保存到txt文件中.. 将日期也一并保存到txt文件中. 输入开始日期和结束日期,就可以统计出每日的次数 代码如下: #!/bin/ ...
- 我的docker笔记
下面的链接全部是我在CSDN的关于docker的博文,我认为已经很是详细了,没有再次总结的必要性,特给出链接地址 docker容器技术基础 https://blog.csdn.net/zisefeiz ...
- SQL模糊查询报:ORA-00909:参数个数无效
用oracle数据库进行模糊查询时,控制台报错如下图所示: 原因是因为敲的太快,语法写错了 正确的写法是 pd.code like concat(concat('%',#{keyword}),'%')
- 箭头函数详解()=>{}
摘要:箭头函数有几个使用注意点. (1)函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象,箭头函数继承而来的this指向永远不变. (2)不可以当作构造函数,也就是说,不可以使用n ...
- sqli-labs(28a)
0X01构造闭合 爆字段数 /?id=') order by 1%23 ?id=') order by 5%23 偷看一下源码 就只过滤了union select 闭合') 那我们来尝试一下 0X02 ...
- 同一个tomcat部署多个项目
在开发项目中,有时候我们需要在同一个tomcat中部署多个项目,小编之前也是遇到了这样的情况,碰过不少的壁,故整理总结如下,以供大家参考.(以Linux为例,其他系统同样适用) 一.首先将需要部署的项 ...
- sklearn 的 PolynomialFeatures 的用法
官方文档:http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.PolynomialFeatures.html ...