1. 程式人生 > >Java的Post方式上傳檔案

Java的Post方式上傳檔案

不說廢話,直接上程式碼:

public void moveWaterMark(String fileName) {
        try {
            File imgFile = new File(fileName);
            if (imgFile.exists()) {
                HttpClient client = new DefaultHttpClient();

                HttpPost httpPost = new HttpPost("http://10.10.10.10:28881/shuiyin/json");
                MultipartEntity entity = new MultipartEntity();
                entity.addPart("pic", new FileBody(imgFile));

                httpPost.setEntity(entity);
                HttpResponse response = client.execute(httpPost);

                HttpEntity responseEntity = response.getEntity();
                String result = EntityUtils.toString(responseEntity);
                System.out.println(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }