httpclient上传文件乱码
Ⅰ commons-httpclient如何实现文件上传
在struts2中结合HttpClient进行文件上传
最近遇到了用httpclient进行上传文件的问题,下面我就和大家简单的说一下:
package com.imps.action;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
public class TabinfoAction extends BaseAction
{
private File[] myFile;
private String[] myFileFileName;// 文件名
private Integer[] myFileFileSize;// 文件大小
private String[] myFileContentType;// 文件类型
public String uploadPost()
{
String posturl ="http://127.0.0.1:8080/settabimage.aspx";
System.out.println(posturl);
String status=null;
for(int i=0;i<myFile.length;i++)
{
FileInputStream file=new FileInputStream(myFile[i]);
InputStream in = new BufferedInputStream(file);
PostMethod post=new PostMethod(posturl);
post.setRequestBody(in);
HttpClient client = new HttpClient();
client.executeMethod(post);
String response=new String(post.getResponseBodyAsString().getBytes("ISO-8859-1"),"UTF-8");
post.releaseConnection();
in.close();
file.close();
}
}
public File[] getMyFile() {
return myFile;
}
public void setMyFile(File[] myFile) {
this.myFile = myFile;
}
public String[] getMyFileFileName() {
return myFileFileName;
}
public void setMyFileFileName(String[] myFileFileName) {
this.myFileFileName = myFileFileName;
}
public Integer[] getMyFileFileSize() {
return myFileFileSize;
}
public void setMyFileFileSize(Integer[] myFileFileSize) {
this.myFileFileSize = myFileFileSize;
}
public String[] getMyFileContentType() {
return myFileContentType;
}
public void setMyFileContentType(String[] myFileContentType) {
this.myFileContentType = myFileContentType;
}
千万记住不要记忘记关闭流和释放http连接
Ⅱ java调http接口 post方式请求 服务器识别全是乱码 服务器识别utf-8的内容 哪位大神知道怎么解决吗
看下你post的方法,设置下这个
httpURLConnection.setRequestProperty("Charset", "utf-8");
拼接参数时:转一下格式
URLEncoder.encode(String.valueOf(value), "utf-8")
下面是我使用的POST方法,最简单的一种
Map<String,String>params=newHashMap<>();//参数
HttpURLConnectionurlCon=null;
URLurlInstance;
StringBuildersbResult=newStringBuilder();
try{
urlInstance=newURL(url);
urlCon=(HttpURLConnection)urlInstance.openConnection();
urlCon.setRequestMethod("POST");
urlCon.setDoOutput(true);//是否可以发送数据到服务器
urlCon.setDoInput(true);//设置是否读服务端
urlCon.setUseCaches(false);//设置是否缓存
urlCon.setConnectTimeout(15000);//设置响应超时
//固定格式
urlCon.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
urlCon.setRequestProperty("Charset","utf-8");
//对参数进行处理
Stringdata="";
if(params!=null){
Stringvalue;
Set<String>set=params.keySet();//获取到所有map的键
for(Stringstring:set){//遍历参数,拼接data
value=params.get(string);
data+=string+"="+URLEncoder.encode(String.valueOf(value),"utf-8")+"&";
}
}
urlCon.setRequestProperty("Content-Length",String.valueOf(data.length()));//设置长度
//往服务器写入数据
OutputStreamout=urlCon.getOutputStream();
out.write(data.getBytes());
out.flush();
//接收服务器返回的数据
InputStreamin=urlCon.getInputStream();
BufferedReaderbr=newBufferedReader(newInputStreamReader(in));
Stringline;//每一行的数据
while((line=br.readLine())!=null){
sbResult.append(line);
}
Ⅲ java HttpPost传入参数中文乱码
以上的2个方法最好都要用上 过滤器只能解决POST请求 ,要处理GET请求就要用
bytes = string.getBytes("iso-8859-1") 得到原始的字节串,再用 string = new String(bytes, "GB2312") 重新得到正确的字符串 。
这个方法,所以最好2个都要写,这样不管是POST还是GET请求就都能解决了。
Ⅳ httpclient get请求返回的数据乱码跪求大神帮帮我..下面是代码,就是一个调用接口返回天气预报json数据
Check if this entry is a directory or a file.
const size_t filenameLength = strlen(fileName);
if (fileName[filenameLength-1] == '/')
{
{
Ⅳ httpclient如何一起上传内容和图片
以文件的形式传参
/**
* 通过拼接的方式构造请求内容,实现参数传输以及文件传输
*
* @param actionUrl 访问的服务器URL
* @param params 普通参数
* @param files 文件参数
* @return
* @throws IOException
*/
public static void post(String actionUrl, Map<String, String> params, Map<String, File> files) throws IOException
{
String BOUNDARY = java.util.UUID.randomUUID().toString();
String PREFIX = "--", LINEND = "\r\n";
String MULTIPART_FROM_DATA = "multipart/form-data";
String CHARSET = "UTF-8";
URL uri = new URL(actionUrl);
HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
conn.setReadTimeout(5 * 1000); // 缓存的最长时间
conn.setDoInput(true);// 允许输入
conn.setDoOutput(true);// 允许输出
conn.setUseCaches(false); // 不允许使用缓存
conn.setRequestMethod("POST");
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
// 首先组拼文本类型的参数
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet())
{
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINEND);
sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);
sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
sb.append(LINEND);
sb.append(entry.getValue());
sb.append(LINEND);
}
DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
outStream.write(sb.toString().getBytes());
InputStream in = null;
// 发送文件数据
if (files != null)
{
for (Map.Entry<String, File> file : files.entrySet())
{
StringBuilder sb1 = new StringBuilder();
sb1.append(PREFIX);
sb1.append(BOUNDARY);
sb1.append(LINEND);
// name是post中传参的键 filename是文件的名称
sb1.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getKey() + "\"" + LINEND);
sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND);
sb1.append(LINEND);
outStream.write(sb1.toString().getBytes());
InputStream is = new FileInputStream(file.getValue());
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1)
{
outStream.write(buffer, 0, len);
}
is.close();
outStream.write(LINEND.getBytes());
}
// 请求结束标志
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
outStream.write(end_data);
outStream.flush();
// 得到响应码
int res = conn.getResponseCode();
if (res == 200)
{
in = conn.getInputStream();
int ch;
StringBuilder sb2 = new StringBuilder();
while ((ch = in.read()) != -1)
{
sb2.append((char) ch);
}
}
outStream.close();
conn.disconnect();
}
// return in.toString();
}
以数据流的形式传参
public static String postFile(String actionUrl, Map<String, String> params, Map<String, byte[]> files)
throws Exception
{
StringBuilder sb2 = null;
String BOUNDARY = java.util.UUID.randomUUID().toString();
String PREFIX = "--", LINEND = "\r\n";
String MULTIPART_FROM_DATA = "multipart/form-data";
String CHARSET = "UTF-8";
URL uri = new URL(actionUrl);
HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
conn.setReadTimeout(6 * 1000); // 缓存的最长时间
conn.setDoInput(true);// 允许输入
conn.setDoOutput(true);// 允许输出
conn.setUseCaches(false); // 不允许使用缓存
conn.setRequestMethod("POST");
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
// 首先组拼文本类型的参数
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet())
{
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINEND);
sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);
sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
sb.append(LINEND);
sb.append(entry.getValue());
sb.append(LINEND);
}
DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
outStream.write(sb.toString().getBytes());
InputStream in = null;
// 发送文件数据
if (files != null)
{
for (Map.Entry<String, byte[]> file : files.entrySet())
{
StringBuilder sb1 = new StringBuilder();
sb1.append(PREFIX);
sb1.append(BOUNDARY);
sb1.append(LINEND);
sb1.append("Content-Disposition: form-data; name=\"pic\"; filename=\"" + file.getKey() + "\"" + LINEND);
sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND);
sb1.append(LINEND);
outStream.write(sb1.toString().getBytes());
// InputStream is = new FileInputStream(file.getValue());
// byte[] buffer = new byte[1024];
// int len = 0;
// while ((len = is.read(buffer)) != -1)
// {
// outStream.write(buffer, 0, len);
// }
// is.close();
outStream.write(file.getValue());
outStream.write(LINEND.getBytes());
}
// 请求结束标志
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
outStream.write(end_data);
outStream.flush();
// 得到响应码
int res = conn.getResponseCode();
if (res == 200)
{
in = conn.getInputStream();
int ch;
sb2 = new StringBuilder();
while ((ch = in.read()) != -1)
{
sb2.append((char) ch);
}
System.out.println(sb2.toString());
}
outStream.close();
conn.disconnect();
// 解析服务器返回来的数据
return ParseJson.getEditMadIconResult(sb2.toString());
}
else
{
return "Update icon Fail";
}
// return in.toString();
}
Ⅵ 请教HttpClient 读取内容乱码的问题
1)将接收的内容(参数)进行编码
request.setCharacterEncodeing(String charset);
2)将要输出的转发的内容进行编码
response.setContextType("text/html;charset=utf-8");
3)html表单中的数据会按照当前页面来进行编码。
<meta http-equiv="content-type" content="text/html;charset=utf-8;">
模拟消息头content-type,让浏览器以utf-8编码打开页面。
确保页面将表单用指定的字符编码进行编码。
4)cookie
cookie的值只能是ascii字符,如果是中文,需要将中文转换成ascii字符形式。
可以使用URLEncoder.encode()方法和URLDecoder.decode()方法来进行这种转换。
5)在web.xml 中配置一个Spring 的编码转换过滤器就可以了.使用在非struts2框架开发:
org.springframework.web.filter.CharacterEncodingFilter
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>
org.springframework.web.filter.CharacterEncodingFilter
</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Ⅶ java的HttpClient请求,返回的数据部分乱码,请大侠指点呀!
可以把你的这段代码简化一下
ins=method.getResponseBodyAsStream();
byte[]b=newbyte[1024];
intr_len=0;
while((r_len=ins.read(b))>0)
{
result.append(newString(b,0,r_len,method.getResponseCharSet()));
}
替换为:
byte[]ba=method.getResponseBody();
Stringstr=newString(ba,"UTF-8"); //得到指定编码格式的字符串
这里的str就是你的返回值。这段代码我使用过,可以解决乱码问题