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就是你的返回值。這段代碼我使用過,可以解決亂碼問題