使用httpclient实现上传下载(javaWeb系统数据传输http实现)

导读:本篇文章讲解 使用httpclient实现上传下载(javaWeb系统数据传输http实现),希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

目的:项目被拆分为两个javaWeb项目,实现项目之间数据传输以及上传、下载功能。 

前台展示项目A,后台提供数据支持项目B

题外话:

两个javaWeb传输之间使用json比较方便,如果恰好使用SpringMVC,配置相关JSON转换工具(功能很强大非常好用),在@Controller层加上@ResponseBody自动将返回值转化成json格式

<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager">		<mvc:message-converters register-defaults="true">			<!-- 将StringHttpMessageConverter的默认编码设为UTF-8 -->			<bean class="org.springframework.http.converter.StringHttpMessageConverter">		    	<constructor-arg value="UTF-8" />			</bean>			<!-- 将Jackson2HttpMessageConverter的默认格式化输出设为true -->			<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">                <property name="prettyPrint" value="true"/>                <property name="objectMapper">                      <bean class="com.fasterxml.jackson.databind.ObjectMapper">                          <property name="dateFormat">                            <bean class="java.text.SimpleDateFormat">                                  <constructor-arg type="java.lang.String" value="yyyy-MM-dd HH:mm:ss" />                              </bean>                          </property>                      </bean>                </property>              </bean>  		</mvc:message-converters>	</mvc:annotation-driven>	<!-- REST中根据URL后缀自动判定Content-Type及相应的View -->	<bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">	    <property name="ignoreAcceptHeader" value="true" />            <property name="defaultContentType" value="application/json" />		    <property name="mediaTypes" >		        <value>		            json=application/json		            xml=application/xml		        </value>		    </property>	</bean>		<!-- jsp配置视图解析 -->	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">		<property name="prefix" value="/WEB-INF/page/"/>		<property name="suffix" value=".jsp"/>	</bean>


进入正题:

上传代码: A调用上传工具类(最头疼的问题就是文件名乱码)

	/**     * 文件上传     * @param is     * @param fileName     * @param url     * @return     */    public static String uploadFile(InputStream is ,String fileName ,String url){        String result = null;        HttpClient httpclient = new DefaultHttpClient();        HttpPost httppost = new HttpPost(url);        //防止文件名乱码        InputStreamBody fileis = new InputStreamBody(is,ContentType.create("text/plain", Consts.UTF_8),fileName);        HttpEntity reqEntity = null;        HttpResponse responses = null;        try {            //BROWSER_COMPATIBLE 设置浏览器为兼容模式  随便设置编码防止乱码            reqEntity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE)                    .addPart("Filedata", fileis).setCharset(CharsetUtils.get("utf-8")).build();            httppost.setEntity(reqEntity);            // 如果需要登陆加上sessionId            httppost.addHeader(new BasicHeader("Cookie", "sessionId=" + clientUser.getSessionId()));            responses = httpclient.execute(httppost);            HttpEntity entity = responses.getEntity();            if(entity != null){                result = EntityUtils.toString(entity, Charset.forName("utf-8"));            }        } catch (UnsupportedEncodingException e) {            e.printStackTrace();        } catch (ClientProtocolException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }                return result;    }

B使用SpringMvc方便得到传入的文件。

@RequestMapping(value="/upload",method=RequestMethod.POST)
	@ResponseBody
	public ModelMap upload(MultipartRequest request){

		ModelMap model = new ModelMap();
		MultipartFile file = request.getFile("Filedata");

		
		String realName= null;
		realName = new Date().getTime() + "_" +file.getOriginalFilename();

		File targetFile = new File(UPLOAD_PATH, realName);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
              //生成文件<pre name="code" class="java">               file.transferTo(targetFile);

return model;}

————————————————————————————

下载

A调用下载  上代码

	/**	 * 文件下载	 * @param url	 * @param fileName	 * @return	 */	public static InputStream fileDownload(String url,String fileName){		CloseableHttpClient  httpclient = new HttpUtils().buildHttpClient();		HttpPost httppost = new HttpPost(url);		StringEntity sEntity = new StringEntity(fileName, Charset.forName("utf-8"));//		BasicNameValuePair basicNameValuePair = new BasicNameValuePair("fileName",fileName);//		List<NameValuePair> list = new ArrayList<NameValuePair>(); //		list.add(basicNameValuePair);//		UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(list, Charset.forName("utf-8"));//   	httppost.setEntity(formEntity);		httppost.setEntity(sEntity);		httppost.addHeader(new BasicHeader("Cookie", "sessionId=" + clientUser.getSessionId()));		httppost.addHeader("Content-Type", "application/xml;charset=utf-8");		try {			CloseableHttpResponse responses = httpclient.execute(httppost);			HttpEntity entity = responses.getEntity();			InputStream content = entity.getContent();			return content;		} catch (ClientProtocolException e) {			// TODO Auto-generated catch block			e.printStackTrace();		} catch (IOException e) {			// TODO Auto-generated catch block			e.printStackTrace();		}				return null;	}



B服务端代码:屏蔽了response.set部分代码,不然会报一个奇怪的错,无法解决。

	    @RequestMapping(value="/fileDownload",method=RequestMethod.POST)    @ResponseBody    public void fileDownload(HttpServletRequest request,HttpServletResponse response){             // getXmlContent获取流传输的文件名,当然也可以使用request.getAttribute获取文件名,需要httpclient做一些设置        String fileName = getXmlContent(request).trim();        System.out.println("开始下载文件....."  + fileName);        try {            File file = new File(DOWNLOAD_PATH + fileName);            if(!file.exists() ||  !file.isFile()){                System.out.println("文件不存在。。" + fileName );                return;            }            //response.setCharacterEncoding("utf-8");            //response.setContentType("multipart/form-data");            //response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);            InputStream inputStream = new FileInputStream(file);            OutputStream os = response.getOutputStream();            byte[] b = new byte[1024];            int length;            while ((length = inputStream.read(b)) > 0) {                os.write(b, 0, length);            }//            Long filelength = file.length();//            byte[] b = new byte[filelength.intValue()];//            inputStream.read(b);//            os.write(b, 0, filelength.intValue());            inputStream.close();        } catch (Exception ex) {            ex.printStackTrace();        }    }


如果服务端A的下载文件为中文名,需要转码

	try {			fileName =  new String(fileName.getBytes("iso8859-1"),"UTF-8");		} catch (UnsupportedEncodingException e1) {			e1.printStackTrace();		}







版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/15914.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!