1. 程式人生 > >httpclient (httppost)上傳檔案 指定格式(text/plain)

httpclient (httppost)上傳檔案 指定格式(text/plain)

public void fileupload(String para1,String para2,String filename,String path){


		HttpClient client = new DefaultHttpClient();
		//超時設定-30s
		client.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT,30000); 
		client.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 30000);
		//介面地址
		HttpPost method = new HttpPost(url);
//		method.setHeader("Content-Type", "multipart/form-data");
		int status = 0;
		try{
			//設定引數
			MultipartEntity entity = new MultipartEntity();
			//第一個引數
			entity.addPart("para1", new StringBody(cdn_id));
			//第二個引數
			entity.addPart("para2", new StringBody(filename));
			//上傳內容
			<span style="color:#ff0000;">FileBody fb = new FileBody(new File(path),"text/plain");</span>
			entity.addPart(filename, fb);
			method.setEntity(entity);
			//執行上傳
			HttpResponse httpresponse = client.execute(method);
			status = httpresponse.getStatusLine().getStatusCode();		//根據返回狀態200等判斷提交是否成功
			if (status == HttpStatus.SC_OK) {
				// --------------------接收返回值---------------------------
				HttpEntity entitysendback = httpresponse.getEntity();
				if (entitysendback != null) {
					InputStream input = entitysendback.getContent();
					BufferedReader br = new BufferedReader(
							new InputStreamReader(input));

					String tempbf;
					StringBuffer html = new StringBuffer();
					while ((tempbf = br.readLine()) != null) {
						html.append(tempbf);
					}
					input.close();
					br.close();

					String result = html.toString();// 返回的json
					JSONObject jsonobject = null;
					int sts = 1;
					try {						//正確返回json,錯誤返回String
jsonobject = JSONObject.fromObject(result);
						sts = Integer.parseInt(jsonobject.getString("status"));
					} catch (Exception e) {
						System.out.println("出錯!原因為:" + result);
						sts = 2;
					}
					// 若提交成功:
					if (sts == 0) {
						addAndDelete(path);
					} else if (sts == 1) {
						System.out.println(jsonobject.getString("error"));
					}
				}
				// 關閉應該關的資源
				EntityUtils.consume(entitysendback);
	            //-----------------------接收返回值結束-----------------------------------
			}else{
				System.out.println(status+"其他未知輸入,請聯絡管理員");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			client.getConnectionManager().shutdown();
		}
	}


而模擬接收的servlet
public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		process(request,response);
	}

	private void process(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException{
			System.out.println("通======================================");
		try 
		   {
			System.out.println(request.getParameter("cdn_id"));
			String filename = request.getParameter("filename");
			System.out.println(filename);
			
		    // Create a factory for disk-based file items
		    DiskFileItemFactory factory = new DiskFileItemFactory();
		    // Set factory constraints
		    factory.setSizeThreshold(4096); // 設定緩衝區大小,這裡是4kb
		    factory.setRepository(tempPathFile);// 設定緩衝區目錄
		    // Create a new file upload handler
		    ServletFileUpload upload = new ServletFileUpload(factory);
		    // Set overall request size constraint
		    upload.setSizeMax(4194304); // 設定最大檔案尺寸,這裡是4MB
		    List<FileItem> items = upload.parseRequest(request);// 得到所有的檔案
		    Iterator<FileItem> i = items.iterator();
		    while (i.hasNext())
		    {
		     FileItem fi = (FileItem) i.next();
		     boolean flag = "text/plain".equals(fi.getContentType());
		     System.out.println("type="+fi.getContentType());
		     System.out.println("是否為txt格式的:"+flag);
		     String fileName = fi.getName();
		     if (fileName != null)
		     {
		      File fullFile = new File(fi.getName());
		      File savedFile = new File(uploadPath, fullFile.getName());
		      fi.write(savedFile);
		     }
		    }
		    System.out.print("upload succeed");
		   }
		   catch (Exception e)
		   {
		    System.out.println(e.getMessage());
		    // 可以跳轉出錯頁面
		    e.printStackTrace();
		   }
	}
	

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		process(request,response);
	}

最近專案要求用http上傳檔案和引數,然後使用httpclient3.1.2開始寫。

官網例子發現最新的httpclient4的方法中都是單獨提交附件的例子,我這還有引數。

於是思考setHeader的事情,忽然想起來,setHeader是整體的,而我只要附件是text/plain格式的,所以只要區域性的格式是text/plain格式的就可以了。
在變換3.x和4.x的過程中發現httppost.setEntity(entity);多次取setEntity取最後一個entity。
參考資料:
MIME頭:http://www.cnblogs.com/lobtao/articles/2954326.html
最終方法發現:http://codego.net/186270/
Multipart/form-data POST檔案上傳詳解:http://www.j2men.com/index.php/archives/955
httpclient4 post上傳:http://blog.csdn.net/sunny243788557/article/details/8106265
response.setContentType()的作用及MIME引數詳解:http://www.jb51.net/article/32773.htm
這裡依然迴歸最開始使用的httpclient3: