Java Post 파일 업로드,결 과 를 파일 로 되 돌려 줍 니 다.

4453 단어 자바
<dependency>
    <groupId>org.apache.httpcomponentsgroupId>
    <artifactId>httpclientartifactId>
    <version>4.3version>

dependency>
<dependency>
    <groupId>org.apache.httpcomponentsgroupId>
    <artifactId>httpmimeartifactId>
    <version>4.3version>
dependency>
public static void main(String[] args) throws Exception {
        byte[] b = getImage("14598222157082.png");
        HttpClient httpClient = HttpClients.createDefault();
        HttpPost httppost = new HttpPost("http://localhost/test");
        MultipartEntityBuilder mEntityBuilder = MultipartEntityBuilder.create();
        mEntityBuilder.addBinaryBody("file",b,ContentType.MULTIPART_FORM_DATA,"14598222157082.png");
        httppost.setEntity(mEntityBuilder.build());
        HttpResponse response = httpClient.execute(httppost);
        Header[] hs= response.getAllHeaders();
        for(Header h:hs)System.out.println(h.getName()+":"+h.getValue());
        InputStream in=response.getEntity().getContent();
        save(in, "result.png");
    }
public static void  save(InputStream in,String path) throws IOException{
        OutputStream out =new FileOutputStream(path);
        int l;
        int n=0;
        //    in.available()        
         while ((l = in.read()) != -1) {
             n++;
             out.write(l);
                }  

        out.flush();
        out.close();
    }

좋은 웹페이지 즐겨찾기