HttpClient Post Form提交文件/二进制数据

HttpClient httpClient = HttpClients.createDefault();
HttpPost httppost = new HttpPost(url);
MultipartEntityBuilder mEntityBuilder = MultipartEntityBuilder.create();
//byte[] postBody
mEntityBuilder.addBinaryBody(postName, postBody);
//提交文件
//File file = new File("test");
//mEntityBuilder.addBinaryBody("name", file);
mEntityBuilder.addTextBody("name", "Value");
httppost.setEntity(mEntityBuilder.build());
HttpResponse responce = httpClient.execute(httppost);

不写成接口:可以直接写在一起

HttpEntity reqEntity = MultipartEntityBuilder.create()
	.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
	.addPart("multipartFile", bin)
	.addPart("userId", userId).setCharset(CharsetUtils.get("UTF-8")).build();

不带参数时:可以直接定义指定的entity

File file = new File("somefile.txt");
FileEntity reqEntity = new FileEntity(file, ContentType.create("text/plain", "UTF-8"));

byte[] b;
ByteArrayEntity entity = new ByteArrayEntity(b) ;

下面是我自己定义的接口:

	/**
	 * Http request :Post
	 *
	 * @param url
	 * @param postBody(Byte)
	 * @param postName
	 * @param params
	 * @param heads
	 * @param timeOut(Millisecond)
	 * @return String of request result
	 */
	public static String postFile(String url, byte[] postBody, String postName, Map params,
			Map heads, Integer timeOut) throws HttpErrorException {
		String reStr = "";
		try {
			HttpClient httpClient = HttpClients.createDefault();
			HttpPost httppost = new HttpPost(url);

			MultipartEntityBuilder mEntityBuilder = MultipartEntityBuilder.create();
			mEntityBuilder.addBinaryBody(postName, postBody);

			if (params != null) {
				// text params
				for (Entry e : params.entrySet()) {
					mEntityBuilder.addTextBody(e.getKey(), e.getValue());
				}
			}

			httppost.setEntity(mEntityBuilder.build());
			if (heads != null) {
				// 一般要求プロパティを設定します
				for (Entry e : heads.entrySet()) {
					httppost.addHeader(e.getKey(), e.getValue());
				}
			}

			// set Timeout
			RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeOut)
					.setConnectTimeout(timeOut).setSocketTimeout(timeOut).build();
			httppost.setConfig(requestConfig);
			// get responce
			HttpResponse responce = httpClient.execute(httppost);
			// get http status code
			int resStatu = responce.getStatusLine().getStatusCode();

			if (resStatu == HttpStatus.SC_OK) {
				// get result data
				HttpEntity entity = responce.getEntity();
				reStr = EntityUtils.toString(entity);
			}
			else {
				log.error(url + ": resStatu is " + resStatu);
				throw new HttpErrorException(url, "resStatu is" + resStatu);
			}
		}
		catch (ConnectionPoolTimeoutException e) {
			log.error("http post throw ConnectionPoolTimeoutException", e);
			throw new HttpErrorException(url, " throw timeout");
		}
		catch (ConnectTimeoutException e) {
			log.error("http post throw ConnectTimeoutException", e);
			throw new HttpErrorException(url, " throw timeout");
		}
		catch (SocketTimeoutException e) {
			log.error("http post throw SocketTimeoutException", e);
			throw new HttpErrorException(url, " throw timeout");
		}
		catch (HttpErrorException e) {
			throw e;
		}
		catch (Exception e) {
			log.error("http post throw Exception", e);
			throw new HttpErrorException(url, " throw Exception");
		}
		return reStr;
	}

posted on 2015-05-14 23:13  colife  阅读(7493)  评论(0编辑  收藏  举报