如何使用httpClent java上传时取得进展

时间:2018-05-26 14:27:24

标签: java apache apache-httpclient-4.x progress

有人可以告诉我如何上传文件进度并在其他课程中使用

任何侦听器或包装器等的使用

public static SusResponseDTO postRequest( String url, String payload, Map< String, String > requestHeaders ) {
    CloseableHttpClient httpClient = null;
    HttpPost httpPost = null;
    CloseableHttpResponse response = null;
    SusResponseDTO susResponseDTO = null;
    try {
        httpClient = HttpClients.createDefault();
        httpPost = new HttpPost( url );

        final StringEntity input = new StringEntity( payload, DEFAULT_ENCODING );
        input.setContentType( JSOM_MIME_TYPE );

        httpPost.setEntity( input );

        for ( final Entry< String, String > h : requestHeaders.entrySet() ) {
            httpPost.addHeader( h.getKey(), h.getValue() );
        }
        response = httpClient.execute( httpPost );

        if ( response.getStatusLine().getStatusCode() != 200 ) {
            throw new SusException( FAILED_HTTP_ERROR_CODE + response.getStatusLine().getStatusCode() );
        }
        for ( Header header : response.getAllHeaders() ) {
            if ( header.getName().equals( SERVER ) && header.getValue().contains( MASTER_SERVER ) ) {
                susResponseDTO = JsonUtils.jsonStreamToObject( response.getEntity().getContent(), SusResponseDTO.class );
                break;
            }
        }

        if ( susResponseDTO == null ) {
            HttpEntity entity = response.getEntity();
            String responseString = EntityUtils.toString( entity, DEFAULT_ENCODING );
            Map< String, String > map = new HashMap<>();
            map = ( Map< String, String > ) JsonUtils.jsonToMap( responseString, map );
            susResponseDTO = JsonUtils.jsonToObject( map.get( RESPONSE_ENTITY ), SusResponseDTO.class );
        }
    } catch ( final IOException e ) {
        ExceptionLogger.logException( e, SuSClient.class );
        throw new SusException( e, SuSClient.class );
    } finally {
        IOUtils.safeClose( response );
        IOUtils.safeClose( httpClient );
    }
    return susResponseDTO;
}

0 个答案:

没有答案