最近在做一個類似手機人人的一個項目,後台寫好以後,我用的是jsp寫的,使用的jar包是smartupload。估計java web的人應該都知道這個東西。
然後在web上測試很正常,然後我就拿出我前一段時間寫過的代碼,結果發現竟然不能用,我不知道是什麼情況,但是我覺得我代碼沒問題,唯一與上次的代碼不同的還是後台,後台用的fileUpload但是我覺得應該不影響呀,不明白怎麼回事,反正就是用下面代碼,可以提交文本資料,圖片資料不知道為啥提交不上去。但是之前的那個項目就能提交上去,今天搞了一天終於搞出一個合適的方法。
1.以前的代碼,(我覺得代碼沒問題,這段代碼可以實現文本資料的提交,圖片資料不知道為啥提交不了,但是不報錯。)代碼沒有注釋,不懂的人可以問我。如果有人知道代碼為啥不能提交表單資料,謝謝指出,小弟我先謝過了。
/** * imitate the form to post all message to the url * * @author Administrator王玉超 * @param strUrl * @param allParams * @param fileParam * @return receive the all message that service machine response to you * based on the param 'strUrl' * @throws Exception */public String submitForm(String strUrl, HashMap<String, String> allParams,HashMap<String, File> fileParam) throws Exception {String BOUNDARY = java.util.UUID.randomUUID().toString();String PREFIX = "--", LINEND = "\r\n";String MULTIPART_FROM_DATA = "multipart/form-data";String CHARSET = "UTF-8";URL url = new URL(strUrl);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setReadTimeout(5 * 1000);conn.setDoInput(true);conn.setDoOutput(true);conn.setUseCaches(false);conn.setInstanceFollowRedirects(true); // 重新導向conn.setRequestMethod("POST");conn.setRequestProperty("connection", "keep-alive");conn.setRequestProperty("Charsert", "UTF-8");conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA+ ";boundary=" + BOUNDARY);conn.connect();// 常值內容上傳StringBuilder strAllParams = new StringBuilder();for (Map.Entry<String, String> param : allParams.entrySet()) {strAllParams.append(PREFIX);strAllParams.append(BOUNDARY);strAllParams.append(LINEND);strAllParams.append("Content-Disposition: form-data; name=\""+ param.getKey() + "\"" + LINEND);strAllParams.append("Content-Type: text/plain; charset=" + CHARSET+ LINEND);strAllParams.append("Content-Transfer-Encoding: 8bit" + LINEND);strAllParams.append(LINEND).append(param.getValue()).append(LINEND);}DataOutputStream dataOutputStream = new DataOutputStream(conn.getOutputStream());dataOutputStream.write(strAllParams.toString().getBytes());// 檔案內容上傳if (fileParam != null) {for (Map.Entry<String, File> file : fileParam.entrySet()) {System.out.println(file.getKey());System.out.println(file.getValue());StringBuilder strFileParam = new StringBuilder();strFileParam.append(PREFIX);strFileParam.append(BOUNDARY);strFileParam.append(LINEND);strFileParam.append("Content-Disposition: form-data; name=\"messageContentPic\"; filename=\""+ file.getKey() + "\"" + LINEND);strFileParam.append("Content-Type: application/octet-stream; charset="+ CHARSET + LINEND);strFileParam.append(LINEND);dataOutputStream.write(strFileParam.toString().getBytes());InputStream input = new FileInputStream(file.getValue());byte[] buffer = new byte[1024 * 5];int len = 0;while ((len = input.read(buffer)) != -1) {dataOutputStream.write(buffer, 0, len);}input.close();dataOutputStream.write(LINEND.getBytes());}}byte[] endData = null;if (fileParam != null) {endData = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();} else {endData = (PREFIX + BOUNDARY + PREFIX).getBytes();}dataOutputStream.write(endData);dataOutputStream.flush();int responseCode = conn.getResponseCode();StringBuilder result = new StringBuilder();System.out.println("相應碼:" + responseCode);if (responseCode == 200) {BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));String readLine = "";while ((readLine = bufferedReader.readLine()) != null) {result.append(readLine);}bufferedReader.close();}dataOutputStream.close();conn.disconnect();return result.toString();}
2.進入正題,今天搗鼓半天,終於弄出一個可以提交圖片的東西。很坑爹呀。需要三個jar檔案。可以去我的資源頁面下載,免費的:http://download.csdn.net/my
commons-httpclient.jar-------------------commons-logging.jar--------------------commons-codec-1.5.jar----------------------反正就是哪裡報錯,就是少哪個jar包,再去下載就行。
這個有個小問題,就是上傳到資料庫中的文字檔都成了%E6%88%91%E6%98%AF%E7%8E%8B%E7%8E%89%E8%B6%85%EF%BC%8C%E8%BF%99%E6%98%AF%E6%88%91httpUtil2%E7%9A%84%E4%B8%80%E4%B8%AA%E6%B5%8B%E8%AF%95這類東西。應該是漢字編碼的一種。反正就是各種問題。覺得很坑爹,不想弄了,貼檔案。
import java.io.BufferedReader;import java.io.File;import java.io.InputStreamReader;import java.net.URLEncoder;import org.apache.commons.httpclient.HttpClient;import org.apache.commons.httpclient.methods.PostMethod;import org.apache.commons.httpclient.methods.multipart.FilePart;import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;import org.apache.commons.httpclient.methods.multipart.Part;import org.apache.commons.httpclient.methods.multipart.StringPart;public class HttpUtil2 {public static void main(String[] args) throws Exception {File f = new File("D:/sk.png");PostMethod filePost = new PostMethod("**************************************自己寫url");Part[] parts = {new FilePart("filename", f),new StringPart("account", "04101055"),new StringPart("collegeId", "3728"),new StringPart("messageKind", "0"),new StringPart("messageContentText", URLEncoder.encode("我是王玉超,這是我httpUtil2的一個測試", "UTF-8")) };filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));HttpClient clients = new HttpClient();int status = clients.executeMethod(filePost);try {BufferedReader rd = new BufferedReader(new InputStreamReader(filePost.getResponseBodyAsStream(), "UTF-8"));StringBuffer stringBuffer = new StringBuffer();String line;while ((line = rd.readLine()) != null) {stringBuffer.append(line);}rd.close();System.out.println("接受到的流是:" + stringBuffer + "—-" + status);} catch (Exception e) {throw new RuntimeException("error", e);}}}
哪位大神有更好的解決辦法趕緊給哥們說說哈。
剛剛把問題解決了。
new StringPart("messageContentText", URLEncoder.encode("王玉超","UTF-8"));將所有的參數的值以byte類型傳遞過去,還要解碼
伺服器端再寫一句話就行了。入下
URLDecoder.decode(“request.geParamter("name")”, "UTF-8");這樣的話就又轉回去了,
無論伺服器端怎麼接受資料,都要把接受來的資料轉碼一下,如果資料正常,那麼就不轉嗎,如果不正常,就轉碼,這樣做有利於防止意外情況發生。