org.apache.http.client.HttpResponseException Java Examples

The following examples show how to use org.apache.http.client.HttpResponseException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Client.java    From geoportal-server-harvester with Apache License 2.0 6 votes vote down vote up
private QueryResponse query(URIBuilder builder, HttpEntity entity) throws IOException, URISyntaxException {
  if (cred != null && !cred.isEmpty()) {
    builder = builder.addParameter("access_token", getAccessToken());
  }

  QueryResponse response = null;
  try {
    response = query(builder.build(), entity);
  } catch (HttpResponseException ex) {
    if (ex.getStatusCode() == 401) {
      clearToken();
      if (cred != null && !cred.isEmpty()) {
        builder = builder.addParameter("access_token", getAccessToken());
      }
      response = query(builder.build(), entity);
    } else {
      throw ex;
    }
  }

  return response;
}
 
Example #2
Source File: AgsClient.java    From geoportal-server-harvester with Apache License 2.0 6 votes vote down vote up
/**
 * Lists folder content.
 *
 * @param folder folder or <code>null</code>
 * @return content response
 * @throws URISyntaxException if invalid URL
 * @throws IOException if accessing token fails
 */
public ContentResponse listContent(String folder) throws URISyntaxException, IOException {
  String url = rootUrl.toURI().resolve("rest/services/").resolve(StringUtils.stripToEmpty(folder)).toASCIIString();
  HttpGet get = new HttpGet(url + String.format("?f=%s", "json"));

  try (CloseableHttpResponse httpResponse = httpClient.execute(get); InputStream contentStream = httpResponse.getEntity().getContent();) {
    if (httpResponse.getStatusLine().getStatusCode()>=400) {
      throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase());
    }
    String responseContent = IOUtils.toString(contentStream, "UTF-8");
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    ContentResponse response = mapper.readValue(responseContent, ContentResponse.class);
    response.url = url;
    return response;
  }
}
 
Example #3
Source File: AgpClient.java    From geoportal-server-harvester with Apache License 2.0 6 votes vote down vote up
/**
 * Reads item metadata.
 * @param itemId item id
 * @param format metadata format
 * @param token token
 * @return item metadata if available
 * @throws URISyntaxException if invalid URL
 * @throws IOException if operation fails
 */
public String readItemMetadata(String itemId, MetadataFormat format, String token) throws IOException, URISyntaxException {
  URIBuilder builder = new URIBuilder(itemMetaUri(itemId));
  
  builder.setParameter("format", (format != null ? format : MetadataFormat.DEFAULT).toString());
  if (token!=null) {
    builder.setParameter("token", token);
  }
  HttpGet req = new HttpGet(builder.build());
  
  try {
    return execute(req, 0);
  } catch (HttpResponseException ex) {
    if (ex.getStatusCode() == 500) {
      return null;
    }
    throw ex;
  }
}
 
Example #4
Source File: HC4DavExchangeSession.java    From davmail with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @inheritDoc
 */
@Override
public int updateFolder(String folderPath, Map<String, String> properties) throws IOException {
    Set<PropertyValue> propertyValues = new HashSet<>();
    if (properties != null) {
        for (Map.Entry<String, String> entry : properties.entrySet()) {
            propertyValues.add(Field.createPropertyValue(entry.getKey(), entry.getValue()));
        }
    }

    ExchangePropPatchRequest propPatchRequest = new ExchangePropPatchRequest(URIUtil.encodePath(getFolderPath(folderPath)), propertyValues);
    try (CloseableHttpResponse response = httpClientAdapter.execute(propPatchRequest)) {
        propPatchRequest.handleResponse(response);
        int status = response.getStatusLine().getStatusCode();
        if (status == HttpStatus.SC_MULTI_STATUS) {
            try {
                status = propPatchRequest.getResponseStatusCode();
            } catch (HttpResponseException e) {
                throw new IOException(e.getMessage(), e);
            }
        }

        return status;
    }
}
 
Example #5
Source File: AbstractResponseHandler.java    From iBioSim with Apache License 2.0 6 votes vote down vote up
protected T parseResponse(StatusLine statusLine, HttpEntity entity, Class<T> pojoClass)
        throws IOException {
    if (statusLine.getStatusCode() >= 400) {
        throw new HttpResponseException(
                statusLine.getStatusCode(),
                statusLine.getReasonPhrase());
    }
    if (entity == null) {
        throw new ClientProtocolException("Response contains no content");
    }
    ContentType contentType = ContentType.getOrDefault(entity);
    Charset charset = contentType.getCharset() != null ? contentType.getCharset() :
            StandardCharsets.UTF_8;

    try (BufferedReader reader = new BufferedReader(
            new InputStreamReader(entity.getContent(), charset))) {
        return unmarshallContent(reader, pojoClass);
    }
}
 
Example #6
Source File: DockerAccessWithHcClient.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
private void doPushImage(String url, Map<String, String> header, HcChunkedResponseHandlerWrapper handler, int status,
                         int retries) throws IOException {
    // 0: The original attemp, 1..retry: possible retries.
    for (int i = 0; i <= retries; i++) {
        try {
            delegate.post(url, null, header, handler, HTTP_OK);
            return;
        } catch (HttpResponseException e) {
            if (isRetryableErrorCode(e.getStatusCode()) && i != retries) {
                log.warn("failed to push image to [{}], retrying...", url);
            } else {
                throw e;
            }
        }
    }
}
 
Example #7
Source File: AsyncHttpResponseHandler.java    From Android-Basics-Codes with Artistic License 2.0 6 votes vote down vote up
@Override
public void sendResponseMessage(HttpResponse response) throws IOException {
    // do not process if request has been cancelled
    if (!Thread.currentThread().isInterrupted()) {
        StatusLine status = response.getStatusLine();
        byte[] responseBody;
        responseBody = getResponseData(response.getEntity());
        // additional cancellation check as getResponseData() can take non-zero time to process
        if (!Thread.currentThread().isInterrupted()) {
            if (status.getStatusCode() >= 300) {
                sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), responseBody, new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()));
            } else {
                sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody);
            }
        }
    }
}
 
Example #8
Source File: TableConverterTest.java    From airtable.java with MIT License 6 votes vote down vote up
@Test
public void testConvertMovie() throws AirtableException, HttpResponseException {

    
    Table<Movie> movieTable = base.table("Movies", Movie.class);
    Movie movie = movieTable.find("recFj9J78MLtiFFMz");
    assertNotNull(movie);
    
    assertEquals(movie.getId(),"recFj9J78MLtiFFMz");
    assertEquals(movie.getName(),"The Godfather");
    assertEquals(movie.getPhotos().size(),2);
    assertEquals(movie.getDirector().size(),1);
    assertEquals(movie.getActors().size(),2);
    assertEquals(movie.getGenre().size(),1);
    //TODO Test für Datum
              
}
 
Example #9
Source File: TableConverterTest.java    From airtable.java with MIT License 6 votes vote down vote up
@Test
public void testConvertAttachement() throws AirtableException, HttpResponseException {

    
    Table<Movie> movieTable = base.table("Movies", Movie.class);
    Movie movie = movieTable.find("recFj9J78MLtiFFMz");
    assertNotNull(movie);
    
    assertEquals(movie.getPhotos().size(),2);
    
    Attachment photo1 = movie.getPhotos().get(0);
    assertNotNull(photo1);
    Attachment photo2 = movie.getPhotos().get(0);
    assertNotNull(photo2);
    
    assertEquals(photo1.getId(),"attk3WY5B28GVcFGU");
    assertEquals(photo1.getUrl(),"https://dl.airtable.com/9UhUUeAtSym1PzBdA0q0_AlPacinoandMarlonBrando.jpg");
    assertEquals(photo1.getFilename(),"AlPacinoandMarlonBrando.jpg");
    assertEquals(photo1.getSize(),35698,0);
    assertEquals(photo1.getType(),"image/jpeg");
    assertEquals(photo1.getThumbnails().size(),2);
    
}
 
Example #10
Source File: Authenticator.java    From LiquidDonkey with MIT License 6 votes vote down vote up
@GuardedBy("lock")
void authenticate(HttpClient client) throws IOException {
    if (id == null || id.isEmpty() || password == null || password.isEmpty()) {
        invalid = "Unable to re-authenticate expired token: missing appleId/ password.";

    } else {
        try {
            Auth auth = Auth.from(client, id, password);

            if (auth.dsPrsID().equals(token.auth().dsPrsID())) {
                token = Token.from(auth);

            } else {
                logger.error("-- reauthentication() > mismatched dsPrsID: {} > {}",
                        token.auth().dsPrsID(), auth.dsPrsID());
                invalid = "Unable to re-authenticate expired token: account mismatch.";
            }
        } catch (HttpResponseException ex) {
            if (ex.getStatusCode() == 401) {
                invalid = "Unable to re-authenticate expired token: invalid appleId/ password.";
            }
        }
    }

    testIsInvalid();
}
 
Example #11
Source File: CustomJenkinsServer.java    From blueocean-plugin with MIT License 6 votes vote down vote up
/**
 * Delete the credential stored in the specified user's domain.
 *
 * @param userName jenkins user name
 * @param domainName name of domain
 * @param credentialId credentialId
 * @throws IOException
 */
public void deleteUserDomainCredential(String userName, String domainName, String credentialId) throws IOException {
    String path = "/user/" + userName + "/credentials/store/user/domain/" + domainName + "/credential/" + credentialId;

    try {
        client.post(path + "/doDelete", false);
        logger.info("deleted credential at " + path);
    } catch (HttpResponseException e) {
        if (e.getStatusCode() == 404) {
            logger.debug("received 404 while trying to delete credential at " + path);
        } else {
            logger.error("error deleting credential at " + path);
            logger.error("message = " + e.getMessage());
            throw e;
        }
    }

}
 
Example #12
Source File: RangeFileAsyncHttpResponseHandler.java    From Android-Basics-Codes with Artistic License 2.0 6 votes vote down vote up
@Override
public void sendResponseMessage(HttpResponse response) throws IOException {
    if (!Thread.currentThread().isInterrupted()) {
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() == HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE) {
            //already finished
            if (!Thread.currentThread().isInterrupted())
                sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), null);
        } else if (status.getStatusCode() >= 300) {
            if (!Thread.currentThread().isInterrupted())
                sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), null, new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()));
        } else {
            if (!Thread.currentThread().isInterrupted()) {
                Header header = response.getFirstHeader(AsyncHttpClient.HEADER_CONTENT_RANGE);
                if (header == null) {
                    append = false;
                    current = 0;
                } else {
                    Log.v(LOG_TAG, AsyncHttpClient.HEADER_CONTENT_RANGE + ": " + header.getValue());
                }
                sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), getResponseData(response.getEntity()));
            }
        }
    }
}
 
Example #13
Source File: DefaultTasksService.java    From geoportal-server-harvester with Apache License 2.0 6 votes vote down vote up
@Override
public DataContent fetchContent(UUID taskId, String recordId, SimpleCredentials credentials) throws DataInputException {
  InputBroker broker = null;
  try {
    TaskDefinition taskDefinition = readTaskDefinition(taskId);
    Task task = this.createTask(taskDefinition);
    
    if (!task.getDataSource().hasAccess(credentials)) {
      throw new HttpResponseException(HttpStatus.SC_UNAUTHORIZED, "Invalid credentials");
    }
    
    broker = newInputBroker(taskDefinition.getSource());
    broker.initialize(new SimpleInitContext(task, new ArrayList<>()));
    
    return broker.readContent(recordId);
  } catch (InvalidDefinitionException|DataProcessorException|HttpResponseException ex) {
    throw new DataInputException(broker, String.format("Error fetching content from: %s -> $s", taskId, recordId), ex);
  } finally {
    if (broker!=null) {
      broker.terminate();
    }
  }
}
 
Example #14
Source File: Client.java    From geoportal-server-harvester with Apache License 2.0 6 votes vote down vote up
private <T> T execute(HttpUriRequest req, Class<T> clazz) throws IOException, URISyntaxException {
  try (CloseableHttpResponse httpResponse = httpClient.execute(req); InputStream contentStream = httpResponse.getEntity().getContent();) {
    String reasonMessage = httpResponse.getStatusLine().getReasonPhrase();
    String responseContent = IOUtils.toString(contentStream, "UTF-8");
    LOG.trace(String.format("RESPONSE: %s, %s", responseContent, reasonMessage));

    if (httpResponse.getStatusLine().getStatusCode() >= 400) {
      T value = null;
      try {
        value = mapper.readValue(responseContent, clazz);
      } catch (Exception ex) {
        throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase());
      }
      if (value == null) {
        throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase());
      }
      return value;
    }

    return mapper.readValue(responseContent, clazz);
  }
}
 
Example #15
Source File: AgsClient.java    From geoportal-server-harvester with Apache License 2.0 6 votes vote down vote up
/**
 * Generates token.
 *
 * @param minutes expiration in minutes.
 * @param credentials credentials.
 * @return token response
 * @throws URISyntaxException if invalid URL
 * @throws IOException if accessing token fails
 */
public TokenResponse generateToken(int minutes, SimpleCredentials credentials) throws URISyntaxException, IOException {
  HttpPost post = new HttpPost(rootUrl.toURI().resolve("tokens/generateToken"));
  HashMap<String, String> params = new HashMap<>();
  params.put("f", "json");
  if (credentials != null) {
    params.put("username", StringUtils.trimToEmpty(credentials.getUserName()));
    params.put("password", StringUtils.trimToEmpty(credentials.getPassword()));
  }
  params.put("client", "requestip");
  params.put("expiration", Integer.toString(minutes));
  HttpEntity entity = new UrlEncodedFormEntity(params.entrySet().stream()
          .map(e -> new BasicNameValuePair(e.getKey(), e.getValue())).collect(Collectors.toList()));
  post.setEntity(entity);

  try (CloseableHttpResponse httpResponse = httpClient.execute(post); InputStream contentStream = httpResponse.getEntity().getContent();) {
    if (httpResponse.getStatusLine().getStatusCode()>=400) {
      throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase());
    }
    String responseContent = IOUtils.toString(contentStream, "UTF-8");
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    return mapper.readValue(responseContent, TokenResponse.class);
  }
}
 
Example #16
Source File: DockerAccessWithHcClient.java    From docker-maven-plugin with Apache License 2.0 6 votes vote down vote up
private void doPushImage(String url, Map<String, String> header, HcChunkedResponseHandlerWrapper handler, int status,
                         int retries) throws IOException {
    // 0: The original attemp, 1..retry: possible retries.
    for (int i = 0; i <= retries; i++) {
        try {
            delegate.post(url, null, header, handler, HTTP_OK);
            return;
        } catch (HttpResponseException e) {
            if (isRetryableErrorCode(e.getStatusCode()) && i != retries) {
                log.warn("failed to push image to [{}], retrying...", url);
            } else {
                throw e;
            }
        }
    }
}
 
Example #17
Source File: TableSelectTest.java    From airtable.java with MIT License 6 votes vote down vote up
@Test
public void testSelectTableSorted() throws AirtableException, HttpResponseException {

    Table table = base.table("Movies", Movie.class);

    List<Movie> retval = table.select(new Sort("Name", Sort.Direction.asc));
    assertNotNull(retval);
    assertEquals(9, retval.size());
    Movie mov = retval.get(0);
    assertEquals("Billy Madison", mov.getName());

    retval = table.select(new Sort("Name", Sort.Direction.desc));
    assertNotNull(retval);
    assertEquals(9, retval.size());
    mov = retval.get(0);
    assertEquals("You've Got Mail", mov.getName());

}
 
Example #18
Source File: AsyncHttpResponseHandler.java    From AndroidWear-OpenWear with MIT License 6 votes vote down vote up
@Override
public void sendResponseMessage(HttpResponse response) throws IOException {
    // do not process if request has been cancelled
    if (!Thread.currentThread().isInterrupted()) {
        StatusLine status = response.getStatusLine();
        byte[] responseBody;
        responseBody = getResponseData(response.getEntity());
        // additional cancellation check as getResponseData() can take non-zero time to process
        if (!Thread.currentThread().isInterrupted()) {
            if (status.getStatusCode() >= 300) {
                sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), responseBody, new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()));
            } else {
                sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody);
            }
        }
    }
}
 
Example #19
Source File: AsyncHttpResponseHandler.java    From Mobike with Apache License 2.0 6 votes vote down vote up
@Override
public void sendResponseMessage(HttpResponse response) throws IOException {
    // do not process if request has been cancelled
    if (!Thread.currentThread().isInterrupted()) {
        StatusLine status = response.getStatusLine();
        byte[] responseBody;
        responseBody = getResponseData(response.getEntity());
        // additional cancellation check as getResponseData() can take non-zero time to process
        if (!Thread.currentThread().isInterrupted()) {
            if (status.getStatusCode() >= 300) {
                sendFailureMessage(status.getStatusCode(), response.getAllHeaders(), responseBody, new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()));
            } else {
                sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody);
            }
        }
    }
}
 
Example #20
Source File: AcquisitionSvcImpl.java    From Lottery with GNU General Public License v2.0 6 votes vote down vote up
public String handleResponse(HttpResponse response)
		throws ClientProtocolException, IOException {
	StatusLine statusLine = response.getStatusLine();
	if (statusLine.getStatusCode() >= 300) {
		throw new HttpResponseException(statusLine.getStatusCode(),
				statusLine.getReasonPhrase());
	}
	HttpEntity entity = response.getEntity();
	if (entity != null) {
		if (!StringUtils.isBlank(charset)) {
			return EntityUtils.toString(entity, charset);
		} else {
			return EntityUtils.toString(entity);
		}
	} else {
		return null;
	}
}
 
Example #21
Source File: HttpRequest.java    From teammates with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Executes a HTTP GET request and returns the response string.
 * @param uri The URI containing the request URL and request parameters.
 * @return the HTTP response string after executing the GET request
 */
public static String executeGetRequest(URI uri) throws IOException {
    HttpUriRequest request = new HttpGet(uri);
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(TIMEOUT_IN_MS).build();

    HttpResponse httpResponse = HttpClientBuilder.create()
                                                 .setDefaultRequestConfig(requestConfig)
                                                 .build()
                                                 .execute(request);
    HttpEntity entity = httpResponse.getEntity();
    String response = EntityUtils.toString(entity, "UTF-8");

    if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        return response;
    } else {
        throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(), response);
    }
}
 
Example #22
Source File: CheckmobiValidationClient.java    From tigase-extension with GNU General Public License v3.0 6 votes vote down vote up
private JsonObject parseResponse(CloseableHttpResponse res) throws IOException {
    try {
        if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity entity = res.getEntity();
            if (entity != null) {
                ContentType contentType = ContentType.getOrDefault(entity);
                Charset charset = contentType.getCharset();
                if (charset == null)
                    charset = Charset.forName("UTF-8");
                Reader reader = new InputStreamReader(entity.getContent(), charset);
                return (JsonObject) new JsonParser().parse(reader);
            }

            // no response body
            return new JsonObject();
        }
        else
            throw new HttpResponseException(
                    res.getStatusLine().getStatusCode(),
                    res.getStatusLine().getReasonPhrase());
    }
    finally {
        res.close();
    }
}
 
Example #23
Source File: HC4DavExchangeSession.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @inheritDoc
 */
@Override
public int createFolder(String folderPath, String folderClass, Map<String, String> properties) throws IOException {
    Set<PropertyValue> propertyValues = new HashSet<>();
    if (properties != null) {
        for (Map.Entry<String, String> entry : properties.entrySet()) {
            propertyValues.add(Field.createPropertyValue(entry.getKey(), entry.getValue()));
        }
    }
    propertyValues.add(Field.createPropertyValue("folderclass", folderClass));

    // standard MkColMethod does not take properties, override ExchangePropPatchRequest instead
    ExchangePropPatchRequest propPatchRequest = new ExchangePropPatchRequest(URIUtil.encodePath(getFolderPath(folderPath)), propertyValues) {
        @Override
        public String getMethod() {
            return "MKCOL";
        }
    };
    int status;
    try (CloseableHttpResponse response = httpClientAdapter.execute(propPatchRequest)) {
        propPatchRequest.handleResponse(response);
        status = response.getStatusLine().getStatusCode();
        if (status == HttpStatus.SC_MULTI_STATUS) {
            status = propPatchRequest.getResponseStatusCode();
        } else if (status == HttpStatus.SC_METHOD_NOT_ALLOWED) {
            LOGGER.info("Folder " + folderPath + " already exists");
        }
    } catch (HttpResponseException e) {
        throw new IOException(e.getMessage(), e);
    }
    LOGGER.debug("Create folder " + folderPath + " returned " + status);
    return status;
}
 
Example #24
Source File: TableSelectJacksonOMTest.java    From airtable.java with MIT License 5 votes vote down vote up
@Test
public void testSelectNonExistingExceptionMessageTable() throws HttpResponseException {

    String message;
    try {
        base.table("NotExists", Movie.class).select();
        message = "Success";
    } catch (AirtableException e) {
        message = e.getMessage();
    }
    assertEquals("Could not find table NotExists in application " + base.name() + " (TABLE_NOT_FOUND) [Http code 404]", message);
}
 
Example #25
Source File: ExportResourceProviderTest.java    From keycloak-export with GNU Affero General Public License v3.0 5 votes vote down vote up
@BeforeClass
public static void initRealmAndUsers() throws IOException {
    Keycloak keycloak = Keycloak.getInstance(KEYCLOAK_URL, "master", "admin", "admin", CLIENT);
    clientBeforeChanges = keycloak.realms().realm("master").clients().findByClientId(CLIENT).get(0);
    createTestUser("admin", "admin", "master", TEST_USER, "password", "user");
    //just making sure realm is not already present
    String token = keycloak.tokenManager().getAccessTokenString();
    RealmRepresentation nullRealm = null;
    try {
        nullRealm = exportRealm(token, TEST_REALM_NAME);
    } catch (HttpResponseException e) {
        Assert.assertEquals(404, e.getStatusCode());
    }
    Assert.assertNull(nullRealm);
    //end just making sure realm is not already present
}
 
Example #26
Source File: SDSReadFeature.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
@Override
public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException {
    try {
        final SDSApiClient client = session.getClient();
        final HttpUriRequest request = new HttpGet(String.format("%s/v4/nodes/files/%s/downloads", client.getBasePath(),
            nodeid.getFileid(file, new DisabledListProgressListener())));
        request.addHeader("X-Sds-Auth-Token", StringUtils.EMPTY);
        if(status.isAppend()) {
            final HttpRange range = HttpRange.withStatus(status);
            final String header;
            if(-1 == range.getEnd()) {
                header = String.format("bytes=%d-", range.getStart());
            }
            else {
                header = String.format("bytes=%d-%d", range.getStart(), range.getEnd());
            }
            if(log.isDebugEnabled()) {
                log.debug(String.format("Add range header %s for file %s", header, file));
            }
            request.addHeader(new BasicHeader(HttpHeaders.RANGE, header));
            // Disable compression
            request.addHeader(new BasicHeader(HttpHeaders.ACCEPT_ENCODING, "identity"));
        }
        final HttpResponse response = client.getClient().execute(request);
        switch(response.getStatusLine().getStatusCode()) {
            case HttpStatus.SC_OK:
            case HttpStatus.SC_PARTIAL_CONTENT:
                return new HttpMethodReleaseInputStream(response);
            default:
                throw new DefaultHttpResponseExceptionMappingService().map("Download {0} failed", new HttpResponseException(
                    response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()), file);
        }
    }
    catch(IOException e) {
        throw new DefaultIOExceptionMappingService().map("Download {0} failed", e, file);
    }
}
 
Example #27
Source File: InputStreamResponseHandler.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
@Override
public InputStream handleResponse(final HttpResponse response) throws IOException {
  final StatusLine statusLine = response.getStatusLine();
  final HttpEntity entity = response.getEntity();
  if (statusLine.getStatusCode() >= 300) {
    EntityUtils.consume(entity);
    throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
  }
  return entity == null ? null : entity.getContent();
}
 
Example #28
Source File: ExchangeDavRequest.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get single Multistatus response.
 *
 * @return response
 * @throws HttpResponseException on error
 */
public MultiStatusResponse getResponse() throws HttpResponseException {
    if (responses == null || responses.size() != 1) {
        throw new HttpResponseException(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase());
    }
    return responses.get(0);
}
 
Example #29
Source File: HttpRequest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
/**
 * Converts thrown exception during BB HTTP call in to JSON serializable {@link ServiceException}
 *
 * @param e exception
 * @return {@link ServiceException} instance
 */
private ServiceException handleException(Exception e){
    if(e instanceof HttpResponseException){
        return new ServiceException(((HttpResponseException) e).getStatusCode(), e.getMessage(), e);
    }
    return new ServiceException.UnexpectedErrorException(e.getMessage(), e);
}
 
Example #30
Source File: SpeedInfo.java    From OpenWokuan with Do What The F*ck You Want To Public License 5 votes vote down vote up
public void refreshInfo() throws UnirestException, HttpResponseException {
    HttpResponse<String> infoResp = Unirest.get("http://bj.wokuan.cn/web/startenrequest.php?ComputerMac={ComputerMac}&ADSLTxt={ADSLTxt}&Type=2&reqsn={reqsn}&oem=00&ComputerId={ComputerId}")
            .routeParam("ComputerMac", rMac)
            .routeParam("ADSLTxt", accID)
            .routeParam("reqsn", genReqSN())
            .routeParam("ComputerId", cID)
            .header("Accept", SpeedBooster.httpAccept)
            .header("Accept-Language", SpeedBooster.httpLang)
            .header("User-Agent", SpeedBooster.httpUA)
            .asString();
    if (infoResp.getStatus() == 200) {
        Document respDoc = Jsoup.parse(infoResp.getBody());
        String[] respArgs = respDoc.getElementById("webcode").text().split("&");
        for (String it : respArgs) {
            String[] kp = it.split("=");
            if (kp[0].equalsIgnoreCase("ov")) actionStatus = kp[1];
            if (kp[0].equalsIgnoreCase("os")) oldSpeed = Integer.parseInt(kp[1]);
            if (kp[0].equalsIgnoreCase("up")) upSpeed = Integer.parseInt(kp[1]);
            if (kp[0].equalsIgnoreCase("glst")) hoursLeft = Float.parseFloat(kp[1]);
            if (kp[0].equalsIgnoreCase("gus")) upSpeedID = kp[1];
            if (kp[0].equalsIgnoreCase("old")) oldSpeedID = kp[1];
            if (kp[0].equalsIgnoreCase("cn")) accID = kp[1];//*
            if (kp[0].equalsIgnoreCase("stu")) isBoosting = kp[1].equals("1");
            if (kp[0].equalsIgnoreCase("random")) ranNum = Integer.parseInt(kp[1]);
        }
    } else
        throw new HttpResponseException(infoResp.getStatus(), infoResp.getStatusText());
}