最近遇到个问题,两个系统共用用户的头像,用户的头像在一个系统中保存,这就涉及到将图片通过scoket发送给另一个系统存储的问题,最初的思路是将图片读成byte[]数组,然后发送,但又发现,发送图片的同时还要发送密钥、uid、username等信息,好通过对方系统的验证,这就不好弄了,最后想出来,将图片读成字符串、然后模拟http post请求,将图片和密钥、uid等信息发送过去,在服务器端,将得到的byte[]数组写进文件中,最后实验真的成功了,我做了整理和消化,也有不足,请指教,代码如下:
- //客户端
- public static String readFileAsString(String fileName) throws Exception {
- FileInputStream fis = new FileInputStream(fileName);
- BufferedInputStream in = new BufferedInputStream(fis);
- byte buffer[] = new byte[256];
- StringBuffer picStr=new StringBuffer();
- BASE64Encoder base64=new BASE64Encoder();
- while (in.read(buffer)>= 0){
- picStr.append(base64.encode(buffer));//进行64位编码
- }
- fis.close();
- fis=null;
- in.close();
- in=null;
- buffer=null;
- return picStr.toString();
- }
- public static void main(String[] a) {
- try {
- File file=new File("c:/雪狼突击队.jpg");
- //将文件读成字符串
- String picString=readFileAsString(file.toString());
- //URLEncode
- picString="picdata="+URLEncoder.encode(picString, "UTF-8");
- String url="http://localhost:8080/Test/index.jsp?uid=1&username=test&auth=098f6bcd4621d373cade4e832627b4f6";
- Socket socket =new Socket(InetAddress.getByName(url),80);
- DataOutputStream dos=new DataOutputStream(socket.getOutputStream());
- String message=""
- +"POST "+url+" HTTP/1.1 \r\n "
- +"Host: test.lingye.com \r\n "+"Accept: */* \r\n "
- +"Cache-Control:no-cache \r\n" +"User-Agent: MSIE6.0; \r\n "
- +"Content-Type: application/x-www-form-urlencoded \r\n "
- +"Content-Length: "+picString.length()+" \r\n "
- +"Connection: Close \r\n\r\n"//报头以两个\n作为结束标志
- +picString+"\r\n ";//post数据
- byte buffer[]=message.getBytes();
- dos.write(buffer);
- dos.flush();
- dos.close();
- //以上只进行了发送操作
- socket.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- //服务器端
- public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- String picdata=request.getParameter("picdata");
- BASE64Decoder base64=new BASE64Decoder();
- //64位解码
- byte[] buffer=base64.decodeBuffer(picdata);
- //写进文件
- FileOutputStream fos=new FileOutputStream("c:/雪狼突击队1.jpg");
- fos.write(buffer);
- fos.flush();
- fos.close();
- fos=null;
- }