天天看點

HttpClient:與springmvc結合跨域請求——使用PostMethod類進行請求,上傳檔案,攜帶參數

1.無參數

public static PostMethod postMethod(String url) {
		return new PostMethod(url);
	}
	
	/**
	 * 通過postMethod類進行請求
	 * @param post
	 */
	public static void sendByPostMethod(PostMethod post) {
		try {
			HttpClient client = new HttpClient();
			int status = client.executeMethod(post);
			if (status == 200) {
				Logger.getLogger(HttpClientUtil.class).info("上傳成功");
				// 輸出響應資訊
				Logger.getLogger(HttpClientUtil.class).info(post.getResponseBodyAsString());
			} else {
				Logger.getLogger(HttpClientUtil.class).info("上傳失敗");
			}
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
           

2.攜帶參數(以上傳檔案為例)

2.1 HttpClientUtil類:

/**
	 * @param file
	 * @param url
	 */
	public static void uploadFileByPostMethod(File file, String url) {
		try {
			PostMethod post = postMethod(url);
			/*
			 * 可以添加多個類型,攜帶多個參數
			 * StringPart
			 * FilePart
			 */
			Part[] parts = {
				new FilePart("file", file)
			};
			MultipartRequestEntity entity = new MultipartRequestEntity(parts, post.getParams());
			/*
			 * entity類型
			 * ByteArrayRequestEntity
			 * InputStreamRequestEntity
			 * MultipartRequestEntity
			 * StringRequestEntity
			 */
			post.setRequestEntity(entity);
			sendByPostMethod(post);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
           

2.2 接收請求接口

@RestController
@RequestMapping("/httpClientController")
public class HttpClientController {

	@RequestMapping(params = "uploadFile")
	public void uploadFile(@RequestParam CommonsMultipartFile file) {
		File serverFile = new File("E:/to/" + file.getOriginalFilename());
		try {
			FileUtils.writeByteArrayToFile(serverFile, file.getBytes());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
           

2.3測試類

@Test
	public void uploadFileByPostMethod() {
		String url = PropUtil.configProp.getProperty("url") + "/httpClientController.do?uploadFile";
		File file = new File("E:/from/test");
		HttpClientUtil.uploadFileByPostMethod(file, url);
	}
           

3.測試檔案

HttpClient:與springmvc結合跨域請求——使用PostMethod類進行請求,上傳檔案,攜帶參數

内容:

HttpClient:與springmvc結合跨域請求——使用PostMethod類進行請求,上傳檔案,攜帶參數

4. 測試結果

HttpClient:與springmvc結合跨域請求——使用PostMethod類進行請求,上傳檔案,攜帶參數
HttpClient:與springmvc結合跨域請求——使用PostMethod類進行請求,上傳檔案,攜帶參數

繼續閱讀