http 请求上传文件

HttpClientUtil.java

 

public class HTTPClientUtil {

    private static Logger log = LoggerFactory.getLogger(HTTPClientUtil.class);

    /**
     * 上传文件
     *
     * @param url
     *            http地址
     * @param fileName
     *            文件路径名称
     * @throws Exception
     */
    public static void postFile(String url, String fileName) throws Exception {
        log.info("Ready Post File:[{}] Url:[{}]", fileName, url);
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        File file = new File(fileName);
        if (file.exists() == false) {
            throw new Exception("File:[" + fileName + "]存在");
        }
        FileEntity fileEntity = new FileEntity(new File(fileName), "UTF-8");
        httppost.addHeader("Content-Type", "text/xml");
        httppost.setEntity(fileEntity);
        try {
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            log.info("Post File:[{}] Url:[{}] Return StatusCode:[{}]",
                    new String[] { fileName, url,
                            response.getStatusLine().toString() });
            if (entity != null) {
                log.info("Response content length: "
                        + entity.getContentLength());
            }
            EntityUtils.consume(entity);
        } catch (Exception e) {
            log.error("Post File:[" + fileName + "] Url:[" + url + "]", e);
        } finally {
            httpclient.getConnectionManager().shutdown();
        }
    }

 

 

 

 

你可能感兴趣的:(http)