• 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;
    	}
  • 相关阅读:
    从运维角度看中大型网站架构的演变之路
    <经验杂谈>Mysql中字符串处理的几种处理方法concat、concat_ws、group_concat
    <经验杂谈>C#使用AES加密解密的简单介绍
    <经验杂谈>C#对CA证书加密解密的简单介绍
    C#实现HttpUtility.UrlEncode输出大写字母
    <微信应用开发系列>定时刷新AccessToken
    <经验杂谈>C#/.Net字符串操作方法小结
    <经验杂谈>查询表结构的SQL语句
    如何在.Net中使用Redis
    ASP.NET MVC进阶之路:深入理解Controller激活机制并使用Ioc容器创建对象
  • 原文地址:https://www.cnblogs.com/colife/p/4504776.html
Copyright © 2020-2023  润新知