利用HttpUrlConnection 上传 接收文件的实现方法
如下所示:
//客户端代码 publicstaticvoidmain(String[]args)throwsIOException{ DataInputStreamin=null; OutputStreamout=null; HttpURLConnectionconn=null; JSONObjectresposeTxt=null; InputStreamins=null; ByteArrayOutputStreamoutStream=null; try{ URLurl=newURL("http://10.28.160.160:9080/main/uploadFile?fileName=列表.txt"); conn=(HttpURLConnection)url.openConnection(); //发送POST请求必须设置如下两行 conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type","text/html"); conn.setRequestProperty("Cache-Control","no-cache"); conn.setRequestProperty("Charsert","UTF-8"); conn.connect(); conn.setConnectTimeout(10000); out=conn.getOutputStream(); Filefile=newFile("H:/Users/chengtingyu/Desktop/test/list.txt"); in=newDataInputStream(newFileInputStream(file)); intbytes=0; byte[]buffer=newbyte[1024]; while((bytes=in.read(buffer))!=-1){ out.write(buffer,0,bytes); } out.flush(); //返回流 if(conn.getResponseCode()==HttpURLConnection.HTTP_OK){ ins=conn.getInputStream(); outStream=newByteArrayOutputStream(); byte[]data=newbyte[1024]; intcount=-1; while((count=ins.read(data,0,1024))!=-1){ outStream.write(data,0,count); } data=null; resposeTxt=JSONObject.parseObject(newString(outStream .toByteArray(),"UTF-8")); } }catch(Exceptione){ e.printStackTrace(); }finally{ if(in!=null){ in.close(); } if(out!=null){ out.close(); } if(ins!=null){ ins.close(); } if(outStream!=null){ outStream.close(); } if(conn!=null){ conn.disconnect(); } } } //服务端代码 publicStringuploadFile()throwsException{ StringfileName=request.getParameter("fileName"); StringfileFullPath="H:/Users/chengtingyu/Desktop/"+fileName; InputStreaminput=null; FileOutputStreamfos=null; try{ input=request.getInputStream(); Filefile=newFile("H:/Users/chengtingyu/Desktop"); if(!file.exists()){ file.mkdirs(); } fos=newFileOutputStream(fileFullPath); intsize=0; byte[]buffer=newbyte[1024]; while((size=input.read(buffer,0,1024))!=-1){ fos.write(buffer,0,size); } //响应信息json字符串格式 Map<String,Object>responseMap=newHashMap<String,Object>(); responseMap.put("flag",true); //生成响应的json字符串 StringjsonResponse=JSONObject.toJSONString(responseMap); sendResponse(jsonResponse); }catch(IOExceptione){ //响应信息json字符串格式 Map<String,Object>responseMap=newHashMap<String,Object>(); responseMap.put("flag",false); responseMap.put("errorMsg",e.getMessage()); StringjsonResponse=JSONObject.toJSONString(responseMap); sendResponse(jsonResponse); }finally{ if(input!=null){ input.close(); } if(fos!=null){ fos.close(); } } returnnull; } /** *返回响应 * *@throwsException */ privatevoidsendResponse(StringresponseString)throwsException{ response.setContentType("application/json;charset=UTF-8"); PrintWriterpw=null; try{ pw=response.getWriter(); pw.write(responseString); pw.flush(); }finally{ IOUtils.closeQuietly(pw); } }
以上这篇利用HttpUrlConnection上传接收文件的实现方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。