View Code
public String postFile(String pathUrl, byte[] data) { StringBuilder sbuilder = new StringBuilder(); try { URL url = new URL(pathUrl); HttpURLConnection httpConn = (HttpURLConnection) url .openConnection(); //设置连接属性 httpConn.setDoOutput(true);// 使用 URL 连接进行输出 httpConn.setDoInput(true);// 使用 URL 连接进行输入 httpConn.setUseCaches(false);// 忽略缓存 httpConn.setRequestMethod("POST");// 设置URL请求方法 // 设置请求属性 httpConn.setRequestProperty("Content-length", "" + data.length); httpConn.setRequestProperty("Content-Type", "application/octet-stream"); httpConn.setRequestProperty("Connection", "Keep-Alive"); httpConn.setRequestProperty("Charset", "UTF-8"); // 建立输出流,并写入数据 OutputStream outputStream = httpConn.getOutputStream(); outputStream.write(data); outputStream.close(); // 获得响应状态 RESPONSE_CODE = httpConn.getResponseCode(); if (HttpURLConnection.HTTP_OK == RESPONSE_CODE) { String readLine; BufferedReader responseReader; // 处理响应流,必须与服务器响应流输出的编码一致 responseReader = new BufferedReader(new InputStreamReader( httpConn.getInputStream(), "UTF-8")); while ((readLine = responseReader.readLine()) != null) { sbuilder.append(readLine); } responseReader.close(); } } catch (Exception ex) { sbuilder.append(ex.getMessage()); ex.printStackTrace(); } return sbuilder.toString(); }
可以直接拷贝下来用。只要将File to byte[]:
View Code
public static byte[] getBytesFromFile(File f){ if(f==null)return null; try { FileInputStream stream = new FileInputStream(f); ByteArrayOutputStream out = new ByteArrayOutputStream(1024); byte[] b = new byte[1024]; for(int n;(n=stream.read(b))!=-1;){ out.write(b,0,n); } stream.close(); out.close(); return out.toByteArray(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }