servlet,接收以POST方式提交来的数据。
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub InputStream inputStream = request.getInputStream(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); String result = ""; try { byte[] data = new byte[1024]; int len = 0; result = ""; if (inputStream != null) { while ((len = inputStream.read(data)) != -1) { byteArrayOutputStream.write(data, 0, len); } result = new String(byteArrayOutputStream.toByteArray()); } } catch (Exception e) { e.printStackTrace(); } finally { byteArrayOutputStream.close(); inputStream.close(); } System.out.println(result); }
post请求时,组织JSON数据并调用servlet传输数据
public static void buildJson() throws Exception { // 图片转换成 BYTE数组 byte[] data = null; FileImageInputStream input = new FileImageInputStream(new File( "d://7.jpg")); ByteArrayOutputStream output = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int numBytesRead = 0; while ((numBytesRead = input.read(buf)) != -1) { output.write(buf, 0, numBytesRead); } data = output.toByteArray(); output.close(); input.close(); JSONObject jo = new JSONObject(); jo.put("agentId", "001"); jo.put("picType", "1"); jo.put("picName", "素材名称"); jo.put("picByte", data); System.out.println(jo.toString()); URL url = new URL( "http://127.0.0.1:8080/AdThirdSystem/UploadServlet"); HttpURLConnection httpURLConnection = (HttpURLConnection) url .openConnection(); httpURLConnection.setConnectTimeout(3000); httpURLConnection.setDoInput(true);// 从服务器获取数据 httpURLConnection.setDoOutput(true);// 向服务器写入数据 OutputStream outputStream = (OutputStream) httpURLConnection .getOutputStream(); outputStream.write(jo.toString().getBytes()); // byte数组 转换成 图片 // FileImageOutputStream imageOutput = new FileImageOutputStream(new File( // "e://1.jpg")); // imageOutput.write(data, 0, data.length); // imageOutput.close(); }