Java Code Examples for org.apache.http.StatusLine#getReasonPhrase()

The following examples show how to use org.apache.http.StatusLine#getReasonPhrase() . 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: SyncHttpHandler.java    From BigApp_Discuz_Android with Apache License 2.0 6 votes vote down vote up
private ResponseStream handleResponse(HttpResponse response) throws HttpException, IOException {
    if (response == null) {
        throw new HttpException("response is null");
    }
    StatusLine status = response.getStatusLine();
    int statusCode = status.getStatusCode();
    if (statusCode < 300) {
        ResponseStream responseStream = new ResponseStream(response, charset, requestUrl, expiry);
        responseStream.setRequestMethod(requestMethod);
        return responseStream;
    } else if (statusCode == 301 || statusCode == 302) {
        if (httpRedirectHandler == null) {
            httpRedirectHandler = new DefaultHttpRedirectHandler();
        }
        HttpRequestBase request = httpRedirectHandler.getDirectRequest(response);
        if (request != null) {
            return this.sendRequest(request);
        }
    } else if (statusCode == 416) {
        throw new HttpException(statusCode, "maybe the file has downloaded completely");
    } else {
        throw new HttpException(statusCode, status.getReasonPhrase());
    }
    return null;
}
 
Example 2
Source File: NiciraRestClient.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
private CloseableHttpResponse execute(final HttpUriRequest request, final int previousStatusCode) throws CloudstackRESTException {
    if (counter.hasReachedExecutionLimit()) {
        throw new CloudstackRESTException("Reached max executions limit of " + executionLimit);
    }
    counter.incrementExecutionCounter();
    s_logger.debug("Executing " + request.getMethod() + " request [execution count = " + counter.getValue() + "]");
    final CloseableHttpResponse response = super.execute(request);

    final StatusLine statusLine = response.getStatusLine();
    final int statusCode = statusLine.getStatusCode();
    s_logger.debug("Status of last request: " + statusLine.toString());
    if (HttpStatusCodeHelper.isUnauthorized(statusCode)) {
        return handleUnauthorizedResponse(request, previousStatusCode, response, statusCode);
    } else if (HttpStatusCodeHelper.isSuccess(statusCode)) {
        return handleSuccessResponse(request, response);
    } else if (HttpStatusCodeHelper.isConflict(statusCode)) {
        throw new CloudstackRESTException("Conflict: " + statusLine.getReasonPhrase(), statusCode);
    } else {
        throw new CloudstackRESTException("Unexpected status code: " + statusCode, statusCode);
    }
}
 
Example 3
Source File: MCRDataciteClient.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
public void deleteMetadata(final MCRDigitalObjectIdentifier doi) throws MCRPersistentIdentifierException {
    URI requestURI = getRequestURI("/metadata/" + doi.asString());

    HttpDelete delete = new HttpDelete(requestURI);
    try (CloseableHttpClient httpClient = getHttpClient()) {
        CloseableHttpResponse response = httpClient.execute(delete);
        StatusLine statusLine = response.getStatusLine();

        switch (statusLine.getStatusCode()) {
            case HttpStatus.SC_OK:
                return;
            case HttpStatus.SC_UNAUTHORIZED:
                throw new MCRDatacenterAuthenticationException();
            case HttpStatus.SC_NOT_FOUND:
                throw new MCRIdentifierUnresolvableException(doi.asString(), doi.asString() + " was not found!");
            default:
                throw new MCRDatacenterException(
                    "Unknown return status: " + statusLine.getStatusCode() + " - " + statusLine.getReasonPhrase());
        }
    } catch (IOException e) {
        throw new MCRDatacenterException("Error while deleting metadata!", e);
    }
}
 
Example 4
Source File: SiteToSiteRestApiClient.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private String execute(final HttpGet get) throws IOException {
    final CloseableHttpClient httpClient = getHttpClient();

    if (logger.isTraceEnabled()) {
        Arrays.stream(get.getAllHeaders()).forEach(h -> logger.debug("REQ| {}", h));
    }

    try (final CloseableHttpResponse response = httpClient.execute(get)) {
        if (logger.isTraceEnabled()) {
            Arrays.stream(response.getAllHeaders()).forEach(h -> logger.debug("RES| {}", h));
        }

        final StatusLine statusLine = response.getStatusLine();
        final int statusCode = statusLine.getStatusCode();
        if (RESPONSE_CODE_OK != statusCode) {
            throw new HttpGetFailedException(statusCode, statusLine.getReasonPhrase(), null);
        }
        final HttpEntity entity = response.getEntity();
        final String responseMessage = EntityUtils.toString(entity);
        return responseMessage;
    }
}
 
Example 5
Source File: HttpRequestException.java    From caravan with Apache License 2.0 6 votes vote down vote up
public HttpRequestException(CloseableHttpResponse response) {
    super(toErrorMessage(response));

    StatusLine statusLine = response.getStatusLine();
    if (statusLine == null)
        return;

    _statusCode = statusLine.getStatusCode();
    _reasonPhrase = statusLine.getReasonPhrase();
    _protocolVersion = statusLine.getProtocolVersion();
    _responseHeaders = response.getAllHeaders();

    HttpEntity entity = response.getEntity();
    if (entity == null)
        return;

    try (InputStream is = entity.getContent();) {
        _responseBody = EntityUtils.toString(entity);
    } catch (Throwable ex) {

    }
}
 
Example 6
Source File: SyncHttpHandler.java    From android-open-project-demo with Apache License 2.0 6 votes vote down vote up
private ResponseStream handleResponse(HttpResponse response) throws HttpException, IOException {
    if (response == null) {
        throw new HttpException("response is null");
    }
    StatusLine status = response.getStatusLine();
    int statusCode = status.getStatusCode();
    if (statusCode < 300) {
        ResponseStream responseStream = new ResponseStream(response, charset, requestUrl, expiry);
        responseStream.setRequestMethod(requestMethod);
        return responseStream;
    } else if (statusCode == 301 || statusCode == 302) {
        if (httpRedirectHandler == null) {
            httpRedirectHandler = new DefaultHttpRedirectHandler();
        }
        HttpRequestBase request = httpRedirectHandler.getDirectRequest(response);
        if (request != null) {
            return this.sendRequest(request);
        }
    } else if (statusCode == 416) {
        throw new HttpException(statusCode, "maybe the file has downloaded completely");
    } else {
        throw new HttpException(statusCode, status.getReasonPhrase());
    }
    return null;
}
 
Example 7
Source File: GerritRestClient.java    From gerrit-rest-java-client with Apache License 2.0 5 votes vote down vote up
private void throwHttpStatusException(HttpResponse response) throws IOException, HttpStatusException {
    StatusLine statusLine = response.getStatusLine();
    String body = "<empty>";
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        body = EntityUtils.toString(entity).trim();
    }
    String message = String.format("Request not successful. Message: %s. Status-Code: %s. Content: %s.",
            statusLine.getReasonPhrase(), statusLine.getStatusCode(), body);
    throw new HttpStatusException(statusLine.getStatusCode(), statusLine.getReasonPhrase(), message);
}
 
Example 8
Source File: TencentResponseHandler.java    From YiBo with Apache License 2.0 5 votes vote down vote up
public String handleResponse(final HttpResponse response) throws HttpResponseException, IOException {
	StatusLine statusLine = response.getStatusLine();
	HttpEntity entity = response.getEntity();
	String jsonStirng = (entity == null ? null : EntityUtils.toString(entity));

	
	Logger.debug("TencentResponseHandler : {}", jsonStirng);

	String dataString = null;
	try {
		JSONObject json = new JSONObject(jsonStirng);
		int res = json.getInt("ret");
		int httpStatusCode = statusLine.getStatusCode();
		switch (res) {
		case 0: // 成功返回
			if (!json.isNull("data")) {
				dataString = json.getString("data");
			} else {
				dataString = "[]";
			}

			break;
		default:
			throw TencentErrorAdaptor.parseError(json);
		}

		if (httpStatusCode >= 300) {
			throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
		}

	} catch (JSONException e) {
		throw new LibRuntimeException(LibResultCode.JSON_PARSE_ERROR, e, ServiceProvider.Tencent);
	}
	return dataString;
}
 
Example 9
Source File: HttpComponentsHttpInvokerRequestExecutor.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Validate the given response as contained in the HttpPost object,
 * throwing an exception if it does not correspond to a successful HTTP response.
 * <p>Default implementation rejects any HTTP status code beyond 2xx, to avoid
 * parsing the response body and trying to deserialize from a corrupted stream.
 * @param config the HTTP invoker configuration that specifies the target service
 * @param response the resulting HttpResponse to validate
 * @throws java.io.IOException if validation failed
 */
protected void validateResponse(HttpInvokerClientConfiguration config, HttpResponse response)
		throws IOException {

	StatusLine status = response.getStatusLine();
	if (status.getStatusCode() >= 300) {
		throw new NoHttpResponseException(
				"Did not receive successful HTTP response: status code = " + status.getStatusCode() +
				", status message = [" + status.getReasonPhrase() + "]");
	}
}
 
Example 10
Source File: AbstractOpenApiService.java    From apollo with Apache License 2.0 5 votes vote down vote up
private void checkHttpResponseStatus(HttpResponse response) {
  if (response.getStatusLine().getStatusCode() == 200) {
    return;
  }

  StatusLine status = response.getStatusLine();
  String message = "";
  try {
    message = EntityUtils.toString(response.getEntity());
  } catch (IOException e) {
    //ignore
  }

  throw new ApolloOpenApiException(status.getStatusCode(), status.getReasonPhrase(), message);
}
 
Example 11
Source File: EtcdClient.java    From jetcd with Apache License 2.0 5 votes vote down vote up
protected JsonResponse extractJsonResponse(HttpResponse httpResponse, int[] expectedHttpStatusCodes) throws EtcdClientException {
    try {
        StatusLine statusLine = httpResponse.getStatusLine();
        int statusCode = statusLine.getStatusCode();

        String json = null;

        if (httpResponse.getEntity() != null) {
            try {
                json = EntityUtils.toString(httpResponse.getEntity());
            } catch (IOException e) {
                throw new EtcdClientException("Error reading response", e);
            }
        }

        if (!contains(expectedHttpStatusCodes, statusCode)) {
            if (statusCode == 400 && json != null) {
                // More information in JSON
            } else {
                throw new EtcdClientException("Error response from etcd: " + statusLine.getReasonPhrase(),
                        statusCode);
            }
        }

        return new JsonResponse(json, statusCode);
    } finally {
        close(httpResponse);
    }
}
 
Example 12
Source File: QQZoneResponseHandler.java    From YiBo with Apache License 2.0 5 votes vote down vote up
public String handleResponse(final HttpResponse response) throws HttpResponseException, IOException {
	StatusLine statusLine = response.getStatusLine();
	HttpEntity entity = response.getEntity();
	String responseString = (entity == null ? null : EntityUtils.toString(entity, "UTF-8"));

	Logger.debug("QQZoneResponseHandler : {}", responseString);

	if (responseString != null) {
		responseString = responseString.trim();
		if (responseString.matches(CALLBACK_RESPONSE_REGEX)) {
			responseString = responseString.replaceAll(CALLBACK_RESPONSE_REGEX, "$1");
		}
		if (responseString.contains("error_code")
			&& responseString.startsWith("{")) {
			try {
				JSONObject json = new JSONObject(responseString);
				if (json.has("error_code")) {
					// 明确是异常响应,而不是包含了error_code的文本
					int errorCode = json.getInt("error_code");
					String errorDesc = json.getString("error");
					String requestPath = json.getString("request");
					throw new LibRuntimeException(
						errorCode, requestPath,	errorDesc, ServiceProvider.QQZone);
				}
			} catch (JSONException e) {
				throw new LibRuntimeException(LibResultCode.JSON_PARSE_ERROR, e, ServiceProvider.QQZone);
			}
		}
	}

	int statusCode = statusLine.getStatusCode();
	if (statusCode >= 300) {
		throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
	}

	return responseString;
}
 
Example 13
Source File: HttpConnHelper.java    From QiQuYingServer with Apache License 2.0 5 votes vote down vote up
/**
 * 创建响应处理器ResponseHandler
 * 
 * @return
 */
public static <T> ResponseHandler<T> prepareResponseHandler(final Class<T> c) {
	ResponseHandler<T> rh = new ResponseHandler<T>() {
		@Override
		public T handleResponse(final HttpResponse response)
				throws IOException {

			StatusLine statusLine = response.getStatusLine();
			HttpEntity entity = response.getEntity();
			if (statusLine.getStatusCode() >= 300) {
				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();
			Reader reader = new InputStreamReader(entity.getContent(),
					charset);
			long hand_start = System.currentTimeMillis();
			T t = gson.fromJson(reader, c);
			long hand_end = System.currentTimeMillis();
			double cost = (hand_end-hand_start)/1000.0;
			log.info("handleResponse convert cost time "+cost+"s");
			return t;
		}
	};
	return rh;
}
 
Example 14
Source File: StringResponseHandler.java    From slack-api with MIT License 5 votes vote down vote up
@Override
public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
	final StatusLine statusLine = response.getStatusLine();
	int status = statusLine.getStatusCode();
	if (status >= 200 && status < 300) {
		HttpEntity entity = response.getEntity();
		return entity != null ? EntityUtils.toString(entity) : null;
	} else if (status == 429) {
		throw new SlackResponseRateLimitException(Long.valueOf(response.getFirstHeader(RETRY_AFTER_HEADER).getValue()));
	} else {
		throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
	}
}
 
Example 15
Source File: InputStreamResponseHandler.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
public InputStream handleResponse(final HttpResponse response) throws HttpResponseException, 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 16
Source File: FacebookSharesButton.java    From android-socialbuttons with Apache License 2.0 5 votes vote down vote up
@Override
protected Long doInBackground(String... uri) {

	HttpClient httpclient = new DefaultHttpClient();
	HttpResponse response;
	Long shares = null;
	try {

		HttpGet getRequest = new HttpGet("http://graph.facebook.com/fql?q=" + URLEncoder.encode("SELECT total_count FROM link_stat WHERE url='" + uri[0] + "'", "UTF-8"));
		response = httpclient.execute(getRequest);
		StatusLine statusLine = response.getStatusLine();
		if(statusLine.getStatusCode() == HttpStatus.SC_OK){
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			response.getEntity().writeTo(out);
			out.close();
			JSONObject result = new JSONObject(out.toString());
			JSONArray data = result.getJSONArray("data");
			shares = ((JSONObject)data.get(0)).getLong("total_count");
		} else{
			//Closes the connection.
			response.getEntity().getContent().close();
			throw new IOException(statusLine.getReasonPhrase());
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	return shares;

}
 
Example 17
Source File: Instapaper.java    From Onosendai with Apache License 2.0 4 votes vote down vote up
static void checkReponseCode (final StatusLine statusLine) throws IOException {
	final int code = statusLine.getStatusCode();
	if (code < 200 || code >= 300) { // NOSONAR not magic numbers.
		throw new IOException("HTTP " + code + ": " + statusLine.getReasonPhrase());
	}
}
 
Example 18
Source File: URIHandle.java    From java-client-api with Apache License 2.0 4 votes vote down vote up
@Override
protected InputStream sendContent() {
  try {
    URI uri = get();
    if (uri == null) {
      throw new IllegalStateException("No uri for input");
    }

    HttpGet method = new HttpGet(uri);

    HttpResponse response = client.execute(method, getContext());

    StatusLine status = response.getStatusLine();
    if (status.getStatusCode() >= 300) {
      if (!method.isAborted()) {
        method.abort();
      }

      throw new MarkLogicIOException("Could not read from "+uri.toString()+": "+status.getReasonPhrase());
    }

    HttpEntity entity = response.getEntity();
    if (entity == null) {
      if (!method.isAborted()) {
        method.abort();
      }

      throw new MarkLogicIOException("Received empty response to write for "+uri.toString());
    }

    InputStream stream = entity.getContent();
    if (stream == null) {
      if (!method.isAborted()) {
        method.abort();
      }

      throw new MarkLogicIOException("Could not get stream to write for "+uri.toString());
    }

    return stream;
  } catch (IOException e) {
    throw new MarkLogicIOException(e);
  }
}
 
Example 19
Source File: HttpClaimInformationPointProvider.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private InputStream executeRequest(HttpFacade httpFacade) {
    String method = config.get("method").toString();

    if (method == null) {
        method = "GET";
    }

    RequestBuilder builder = null;

    if ("GET".equalsIgnoreCase(method)) {
        builder = RequestBuilder.get();
    } else {
        builder = RequestBuilder.post();
    }

    builder.setUri(config.get("url").toString());

    byte[] bytes = new byte[0];

    try {
        setParameters(builder, httpFacade);

        if (config.containsKey("headers")) {
            setHeaders(builder, httpFacade);
        }

        HttpResponse response = httpClient.execute(builder.build());
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            bytes = EntityUtils.toByteArray(entity);
        }

        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();

        if (statusCode < 200 || statusCode >= 300) {
            throw new HttpResponseException("Unexpected response from server: " + statusCode + " / " + statusLine.getReasonPhrase(), statusCode, statusLine.getReasonPhrase(), bytes);
        }

        return new ByteArrayInputStream(bytes);
    } catch (Exception cause) {
        try {
            throw new RuntimeException("Error executing http method [" + builder + "]. Response : " + StreamUtil.readString(new ByteArrayInputStream(bytes), Charset.forName("UTF-8")), cause);
        } catch (Exception e) {
            throw new RuntimeException("Error executing http method [" + builder + "]", cause);
        }
    }
}
 
Example 20
Source File: ApacheHttpResponse.java    From google-http-java-client with Apache License 2.0 4 votes vote down vote up
@Override
public String getReasonPhrase() {
  StatusLine statusLine = response.getStatusLine();
  return statusLine == null ? null : statusLine.getReasonPhrase();
}