本例通过java模拟了Http的request请求,请求格式为multipart,实现了向服务器同时传递json数据和图片数据。
1 import java.io.ByteArrayOutputStream; 2 import java.io.File; 3 import java.io.FileInputStream; 4 import java.io.FileNotFoundException; 5 import java.io.IOException; 6 import java.io.InputStream; 7 import java.io.OutputStream; 8 import java.net.HttpURLConnection; 9 import java.net.MalformedURLException; 10 import java.net.URL; 11 12 public class HttpMultipartTest { 13 static String boundary = "abcde12345"; 14 static String prefix = "--"; 15 static String newLine = "\r\n"; 16 17 public static void main(final String args[]) { 18 test(); 19 } 20 21 private static void test() { 22 try { 23 URL url = new URL("http://127.0.0.1:8080/httpMultipartTestServer/App/testMultipart"); 24 HttpURLConnection connection = (HttpURLConnection)url.openConnection(); 25 connection.setDoInput(true); 26 connection.setDoOutput(true); 27 connection.setRequestProperty("Content-type", "multipart/form-data;boundary=" + boundary); 28 ConfigHttpMultipart(connection.getOutputStream()); 29 InputStream ins = connection.getInputStream(); 30 byte[] b = readBuffer(ins); 31 System.out.println(new String(b)); 32 } catch (MalformedURLException e) { 33 System.out.println(" url error! "); 34 } catch (IOException e) { 35 System.out.println(" io error! "); 36 } 37 } 38 39 private static void ConfigHttpMultipart(final OutputStream out) { 40 StringBuffer params = new StringBuffer(); 41 params.append(prefix + boundary + newLine); 42 params.append("Content-Disposition: form-data; name=\"jsonData\""); 43 params.append(newLine + newLine); 44 String jsonData = "{\"test\":\"test message!\"}"; 45 params.append(jsonData); 46 params.append(newLine); 47 params.append(prefix + boundary + newLine); 48 params.append("Content-Disposition: form-data; name=\"signature\"; filename=\"test.jpg\""); 49 params.append(newLine); 50 params.append("Content-Type: image/pjpeg"); 51 params.append(newLine + newLine); 52 File file = new File("C://test.jpg"); 53 try { 54 InputStream in = new FileInputStream(file); 55 out.write(params.toString().getBytes()); 56 out.write(readBuffer(in)); 57 out.write(newLine.getBytes()); 58 out.write((prefix + boundary + prefix + newLine).getBytes()); 59 out.flush(); 60 out.close(); 61 } catch (FileNotFoundException e) { 62 System.out.println(" no file! "); 63 } catch (IOException e) { 64 System.out.println(" io error! "); 65 } 66 } 67 68 public static byte[] readBuffer(final InputStream ins) throws IOException { 69 byte b[] = new byte[1024]; 70 ByteArrayOutputStream stream = new ByteArrayOutputStream(); 71 int len = 0; 72 while ((len = ins.read(b)) != -1) { 73 stream.write(b, 0, len); 74 } 75 return stream.toByteArray(); 76 } 77 }