Java Code Examples for org.apache.http.HttpResponse#getStatusLine()

The following examples show how to use org.apache.http.HttpResponse#getStatusLine() . 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: GoHttpClientHttpInvokerRequestExecutor.java    From gocd with Apache License 2.0 6 votes vote down vote up
private void validateResponse(HttpResponse response) throws IOException {
    StatusLine status = response.getStatusLine();
    if (status.getStatusCode() >= 400) {
        String messagePrefix = String.format("The server returned status code %d. Possible reasons include:", status.getStatusCode());

        List<String> reasons = Arrays.asList(
                "This agent has been deleted from the configuration",
                "This agent is pending approval",
                "There is possibly a reverse proxy (or load balancer) that has been misconfigured. See "
                        + docsUrl("/installation/configure-reverse-proxy.html#agents-and-reverse-proxies") +
                        " for details."
        );

        String delimiter = "\n   - ";
        throw new ClientProtocolException(messagePrefix + delimiter + String.join(delimiter, reasons));
    }
    if (status.getStatusCode() >= 300) {
        throw new NoHttpResponseException("Did not receive successful HTTP response: status code = " + status.getStatusCode() + ", status message = [" + status.getReasonPhrase() + "]");
    }

}
 
Example 2
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 3
Source File: BitlyUrlService.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * Makes a GET request to the given address. Any query string should be appended already.
 * @param address	the fully qualified URL to make the request to
 * @return
 */
private String doGet(String address){
	try {
		
		HttpClient httpclient = new DefaultHttpClient();
		HttpGet httpget = new HttpGet(address);
		HttpResponse response = httpclient.execute(httpget);
		
		//check reponse code
		StatusLine status = response.getStatusLine();
		if(status.getStatusCode() != 200) {
			log.error("Error shortening URL. Status: " + status.getStatusCode() + ", reason: " + status.getReasonPhrase());
			return null;
		}
		
		HttpEntity entity = response.getEntity();
		if (entity != null) {
		    return EntityUtils.toString(entity);
		}
		
	} catch (Exception e) {
		log.error(e.getClass() + ":" + e.getMessage());
	} 
	return null;
}
 
Example 4
Source File: AbstractRequest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
protected void checkResponse(
        final ODataClient odataClient, final HttpResponse response, final String accept) {

  if (response.getStatusLine().getStatusCode() >= 400) {
    Header contentTypeHeader = response.getEntity() != null ? response.getEntity().getContentType() : null;
    try {
      final ODataRuntimeException exception = ODataErrorResponseChecker.checkResponse(
              odataClient,
              response.getStatusLine(),
              response.getEntity() == null ? null : response.getEntity().getContent(),
                  (contentTypeHeader != null && 
                  contentTypeHeader.getValue().contains(TEXT_CONTENT_TYPE)) ? TEXT_CONTENT_TYPE : accept);
      if (exception != null) {
        if (exception instanceof ODataClientErrorException) {
          ((ODataClientErrorException)exception).setHeaderInfo(response.getAllHeaders());
        }
        throw exception;
      }
    } catch (IOException e) {
      throw new ODataRuntimeException(
              "Received '" + response.getStatusLine() + "' but could not extract error body", e);
    }
  }
}
 
Example 5
Source File: HttpWrapper.java    From Android-Material-Icons with Apache License 2.0 6 votes vote down vote up
static String makeRequest(String uri) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response;
    String responseString = null;
    try {
        response = httpclient.execute(new HttpGet(uri));
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            responseString = out.toString();
            out.close();
        } else {
            //Close the connection.
            response.getEntity().getContent().close();
            throw new IOException(statusLine.getReasonPhrase());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return responseString;
}
 
Example 6
Source File: FanfouResponseHandler.java    From YiBo with Apache License 2.0 6 votes vote down vote up
@Override
	public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
		StatusLine statusLine = response.getStatusLine();
		HttpEntity entity = response.getEntity();
		String responseString = (entity == null ? null : EntityUtils.toString(entity));

		
		logger.debug("FanfouResponseHandler : {}", responseString);

		if (statusLine.getStatusCode() != 200) {
			//TODO: 貌似饭否没有错误信息说明,如果有的话,这里要补上
//			JSONObject json = null;
//			try {
//				json = new JSONObject(responseString);
//				LibRuntimeException apiException =  FanfouErrorAdaptor.parseError(json);
//				throw apiException;
//			} catch (JSONException e) {
//				throw new LibRuntimeException(ExceptionCode.JSON_PARSE_ERROR, e, ServiceProvider.Fanfou);
//			}
			throw new LibRuntimeException(LibResultCode.E_UNKNOWN_ERROR, ServiceProvider.Fanfou);
		}
		return responseString;
	}
 
Example 7
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 8
Source File: ToopherAPI.java    From oxAuth with MIT License 6 votes vote down vote up
@Override
public JSONObject 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(); // TODO: check entity == null
    String json = EntityUtils.toString(entity);

    try {
        return (JSONObject) new JSONTokener(json).nextValue();
    } catch (JSONException e) {
        throw new ClientProtocolException("Could not interpret response as JSON", e);
    }
}
 
Example 9
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 10
Source File: Utf8ResponseHandler.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
public String 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 : EntityUtils.toString(entity, Consts.UTF_8);
}
 
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: SolrClient.java    From yarn-proto with Apache License 2.0 5 votes vote down vote up
public Map<String,Object> handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
  HttpEntity entity = response.getEntity();
  if (entity != null) {
    Object resp = ObjectBuilder.getVal(new JSONParser(EntityUtils.toString(entity)));
    if (resp != null && resp instanceof Map) {
      return (Map<String,Object>)resp;
    } else {
      throw new ClientProtocolException("Expected JSON object in response but received "+ resp);
    }
  } else {
    StatusLine statusLine = response.getStatusLine();
    throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
  }
}
 
Example 13
Source File: ApacheHttpClientDelegate.java    From docker-maven-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public T handleResponse(HttpResponse response) throws IOException {
    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    for (int code : statusCodes) {
        if (statusCode == code) {
            return delegate.handleResponse(response);
        }
    }

    String reason = statusLine.getReasonPhrase().trim();
    throw new HttpRequestException(String.format("%s (%s: %d)", getResponseMessage(response),
                                                 reason, statusCode));
}
 
Example 14
Source File: DefaultCosHttpClient.java    From markdown-image-kit with MIT License 5 votes vote down vote up
private boolean isRequestSuccessful(HttpResponse httpResponse) {
    StatusLine statusLine = httpResponse.getStatusLine();
    int statusCode = -1;
    if (statusLine != null) {
        statusCode = statusLine.getStatusCode();
    }
    return statusCode / 100 == HttpStatus.SC_OK / 100;
}
 
Example 15
Source File: HopServer.java    From hop with Apache License 2.0 5 votes vote down vote up
public String execService( String service, Map<String, String> headerValues ) throws Exception {
  // Prepare HTTP get
  HttpGet method = buildExecuteServiceMethod( service, headerValues );
  // Execute request
  try {
    HttpResponse httpResponse = getHttpClient().execute( method, getAuthContext() );
    StatusLine statusLine = httpResponse.getStatusLine();
    int statusCode = statusLine.getStatusCode();

    // The status code
    if ( log.isDebug() ) {
      log.logDebug(
        BaseMessages.getString( PKG, "HopServer.DEBUG_ResponseStatus", Integer.toString( statusCode ) ) );
    }

    String responseBody = getResponseBodyAsString( httpResponse.getEntity().getContent() );

    if ( log.isDetailed() ) {
      log.logDetailed( BaseMessages.getString( PKG, "HopServer.DETAILED_FinishedReading", Integer
        .toString( responseBody.getBytes().length ) ) );
    }
    if ( log.isDebug() ) {
      log.logDebug( BaseMessages.getString( PKG, "HopServer.DEBUG_ResponseBody", responseBody ) );
    }

    if ( statusCode >= 400 ) {
      throw new HopException( String.format( "HTTP Status %d - %s - %s", statusCode, method.getURI().toString(),
        statusLine.getReasonPhrase() ) );
    }

    return responseBody;
  } finally {
    // Release current connection to the connection pool once you are done
    method.releaseConnection();
    if ( log.isDetailed() ) {
      log.logDetailed( BaseMessages.getString( PKG, "HopServer.DETAILED_ExecutedService", service, hostname ) );
    }
  }
}
 
Example 16
Source File: START.java    From NLIWOD with GNU Affero General Public License v3.0 5 votes vote down vote up
public void search(IQuestion question, String language) throws Exception {
	String questionString;
	if (!question.getLanguageToQuestion().containsKey(language)) {
		return;
	}
	questionString = question.getLanguageToQuestion().get(language);
	log.debug(this.getClass().getSimpleName() + ": " + questionString);

	RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(this.timeout).build();
	HttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
	
	URIBuilder builder = new URIBuilder().setScheme("http")
			.setHost("start.csail.mit.edu").setPath("/justanswer.php")
			.setParameter("query", questionString);
	if(this.setLangPar){
		builder = builder.setParameter("lang", language);
	}
	URI uri = builder.build();
	HttpGet httpget = new HttpGet(uri);
	HttpResponse response = client.execute(httpget);
	//Test if error occured
	if(response.getStatusLine().getStatusCode()>=400){
		throw new Exception("START Server could not answer due to: "+response.getStatusLine());
	}
	
	Document doc = Jsoup.parse(responseparser.responseToString(response));
	System.out.println(doc.select("span[type=reply]").text());

	// TODO return senseful answer from start
	// return resultSet;
}
 
Example 17
Source File: MwsAQCall.java    From amazon-mws-orders with Apache License 2.0 5 votes vote down vote up
/**
 * Perform a synchronous call with error handling and back-off/retry.
 * 
 * @return A MwsReader to read the response from.
 */
@Override
public MwsReader invoke() {
    HttpPost request = createRequest();
    for (int retryCount = 0;;retryCount++) {
        try {
            HttpResponse response = executeRequest(request);
            StatusLine statusLine = response.getStatusLine();
            int status = statusLine.getStatusCode();
            String message = statusLine.getReasonPhrase();
            rhmd = getResponseHeaderMetadata(response);
            String body = getResponseBody(response);
            if (status == HttpStatus.SC_OK) {
                return new MwsXmlReader(body);
            }
            if (status == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
                if (pauseIfRetryNeeded(retryCount)) {
                    continue;
                }
            }
            throw new MwsException(status, message, null, null, body, rhmd);
        } catch (Exception e) {
            throw MwsUtl.wrap(e);
        } finally {
            request.releaseConnection();
        }
    }
}
 
Example 18
Source File: NamespaceManager.java    From azure-notificationhubs-java-backend with Apache License 2.0 5 votes vote down vote up
private String getErrorString(HttpResponse response)
		throws IllegalStateException, IOException {
	StringWriter writer = new StringWriter();
	IOUtils.copy(response.getEntity().getContent(), writer, "UTF-8");
	String body = writer.toString();
	return "Error: " + response.getStatusLine() + " - " + body;
}
 
Example 19
Source File: ErrorResponse.java    From knox with Apache License 2.0 4 votes vote down vote up
ErrorResponse(String text, HttpResponse response) {
  super(text + response.getStatusLine());
  this.response = response;
}
 
Example 20
Source File: SpringBreakCve20178046.java    From java-examples with MIT License 4 votes vote down vote up
/**
 * HTTP PATCH operation on the target passing the malicious payload.
 *
 * @param payload
 *            The malicious payload.
 * @return The response as a string.
 * @throws IOException
 *             If something bad occurs during HTTP GET.
 */
private String httpPatch(String payload) throws IOException {
    System.out.println("[*] Sending payload.");

    // Preparing PATCH operation.
    HttpClient client = HttpClientBuilder.create().build();
    HttpPatch patch = new HttpPatch(this.url);
    patch.setHeader("User-Agent", "Mozilla/5.0");
    patch.setHeader("Accept-Language", "en-US,en;q=0.5");
    patch.setHeader("Content-Type", "application/json-patch+json"); // This is a JSON Patch.
    if (!isEmpty(this.cookies)) {
        patch.setHeader("Cookie", this.cookies);
    }
    System.out.println(new StringEntity(payload));
    patch.setEntity(new StringEntity(payload));

    // Response string.
    StringBuffer response = new StringBuffer();

    // Executing PATCH operation.
    HttpResponse httpResponse = client.execute(patch);
    if (httpResponse != null) {

        // Reading response code.
        if (httpResponse.getStatusLine() != null) {
            int responseCode = httpResponse.getStatusLine().getStatusCode();
            System.out.println("[*] HTTP " + responseCode);
        } else {
            System.out.println("[!] HTTP response code can't be read.");
        }

        // Reading response content.
        if (httpResponse.getEntity() != null && httpResponse.getEntity().getContent() != null) {
            BufferedReader in = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
            String inputLine;

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
                response.append(System.getProperty("line.separator"));
            }
            in.close();
        } else {
            System.out.println("[!] HTTP response content can't be read.");
        }

    } else {
        System.out.println("[!] HTTP response is null.");
    }

    return response.toString();
}