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

The following examples show how to use org.apache.http.HttpResponse#containsHeader() . 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: DefaultHttpRequestProcessor.java    From sofa-lookout with Apache License 2.0 6 votes vote down vote up
public void handleErrorResponse(HttpResponse response, HttpRequestBase request) {
    int status = response.getStatusLine().getStatusCode();
    Header header = response.getFirstHeader("Err");
    String errMsg = (header != null && header.getValue() != null) ? header.getValue() : "";
    if (401 == status) {
        logger.info(">>WARNING: Unauthorized!msg:{},request:{}", errMsg, request.toString());
    } else if (403 == status) {
        logger.info(">>WARNING: Forbidden!msg:{},request:{}", errMsg, request.toString());
    } else if (404 == status) {
        logger.debug(">>WARNING: ResourceNotFound!msg:{},request:{}", errMsg,
            request.toString());
    } else if (555 == status) {
        logger.info(">>WARNING: gateway current limit!msg:{},request:{}", errMsg,
            request.toString());
    } else {
        logger.info(">>WARNING: send to gateway fail!status:{}!msg:{}request:{}", status,
            errMsg, request.toString());
    }
    //change silentTime
    if (response.containsHeader(WAIT_MINUTES)) {
        String waitMinutesStr = response.getFirstHeader(WAIT_MINUTES).getValue();
        changeSilentTime(waitMinutesStr);
    }
}
 
Example 2
Source File: APIManagerAdapter.java    From apimanager-swagger-promote with Apache License 2.0 6 votes vote down vote up
private static APISpecification getOriginalAPIDefinitionFromAPIM(String backendApiID) throws AppException {
	URI uri;
	APISpecification apiDefinition;
	HttpResponse httpResponse = null;
	try {
		uri = new URIBuilder(CommandParameters.getInstance().getAPIManagerURL()).setPath(RestAPICall.API_VERSION + "/apirepo/"+backendApiID+"/download")
				.setParameter("original", "true").build();
		RestAPICall getRequest = new GETRequest(uri, null);
		httpResponse=getRequest.execute();
		String res = EntityUtils.toString(httpResponse.getEntity(),StandardCharsets.UTF_8);
		String origFilename = "Unkown filename";
		if(httpResponse.containsHeader("Content-Disposition")) {
			origFilename = httpResponse.getHeaders("Content-Disposition")[0].getValue();
		}
		apiDefinition = APISpecificationFactory.getAPISpecification(res.getBytes(StandardCharsets.UTF_8), origFilename.substring(origFilename.indexOf("filename=")+9), null);
		return apiDefinition;
	} catch (Exception e) {
		throw new AppException("Can't read Swagger-File.", ErrorCode.CANT_READ_API_DEFINITION_FILE, e);
	} finally {
		try {
			if(httpResponse!=null) 
				((CloseableHttpResponse)httpResponse).close();
		} catch (Exception ignore) {}
	}
}
 
Example 3
Source File: APIManagerAdapter.java    From apimanager-swagger-promote with Apache License 2.0 6 votes vote down vote up
private static APIImage getAPIImageFromAPIM(String backendApiID) throws AppException {
	APIImage image = new APIImage();
	URI uri;
	HttpResponse httpResponse = null;
	try {
		uri = new URIBuilder(CommandParameters.getInstance().getAPIManagerURL()).setPath(RestAPICall.API_VERSION + "/proxies/"+backendApiID+"/image").build();
		RestAPICall getRequest = new GETRequest(uri, null);
		httpResponse = getRequest.execute();
		if(httpResponse == null || httpResponse.getEntity() == null) return null; // no Image found in API-Manager
		InputStream is = httpResponse.getEntity().getContent();
		image.setImageContent(IOUtils.toByteArray(is));
		image.setBaseFilename("api-image");
		if(httpResponse.containsHeader("Content-Type")) {
			String contentType = httpResponse.getHeaders("Content-Type")[0].getValue();
			image.setContentType(contentType);
		}
		return image;
	} catch (Exception e) {
		throw new AppException("Can't read Image from API-Manager.", ErrorCode.API_MANAGER_COMMUNICATION, e);
	} finally {
		try {
			if(httpResponse!=null) 
				((CloseableHttpResponse)httpResponse).close();
		} catch (Exception ignore) {}
	}
}
 
Example 4
Source File: CsrfHttpClient.java    From multiapps-controller with Apache License 2.0 6 votes vote down vote up
private String fetchNewCsrfToken() throws IOException {
    if (csrfGetTokenUrl == null) {
        return null;
    }

    HttpGet fetchTokenRequest = new HttpGet(csrfGetTokenUrl);
    fetchTokenRequest.addHeader(CSRF_TOKEN_HEADER_NAME, CSRF_TOKEN_HEADER_FETCH_VALUE);
    setHttpRequestHeaders(fetchTokenRequest);
    HttpResponse response = delegate.execute(fetchTokenRequest);
    EntityUtils.consume(response.getEntity());
    if (response.containsHeader(CSRF_TOKEN_HEADER_NAME)) {
        return response.getFirstHeader(CSRF_TOKEN_HEADER_NAME)
                       .getValue();
    }

    return null;
}
 
Example 5
Source File: DXHTTPRequest.java    From dxWDL with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the value of a given header from an HttpResponse
 *
 * @param response the HttpResponse Object
 *
 * @param headerName name of the header to extract the value
 */
private static String getHeader(HttpResponse response, String headerName) {
    String headerValue = "";
    if (response.containsHeader(headerName)) {
        headerValue = response.getFirstHeader(headerName).getValue();
    }
    return headerValue;
}
 
Example 6
Source File: DefaultHttpRedirectHandler.java    From BigApp_Discuz_Android with Apache License 2.0 5 votes vote down vote up
@Override
public HttpRequestBase getDirectRequest(HttpResponse response) {
    if (response.containsHeader("Location")) {
        String location = response.getFirstHeader("Location").getValue();
        HttpGet request = new HttpGet(location);
        if (response.containsHeader("Set-Cookie")) {
            String cookie = response.getFirstHeader("Set-Cookie").getValue();
            request.addHeader("Cookie", cookie);
        }
        return request;
    }
    return null;
}
 
Example 7
Source File: ProxyFacetSupport.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private void mayThrowBypassHttpErrorException(final HttpResponse httpResponse) {
  final StatusLine status = httpResponse.getStatusLine();
  if (httpResponse.containsHeader(BYPASS_HTTP_ERRORS_HEADER_NAME)) {
    log.debug("Bypass http error: {}", status);
    ListMultimap<String, String> headers = ArrayListMultimap.create();
    headers.put(BYPASS_HTTP_ERRORS_HEADER_NAME, BYPASS_HTTP_ERRORS_HEADER_VALUE);
    HttpClientUtils.closeQuietly(httpResponse);
    throw new BypassHttpErrorException(status.getStatusCode(), status.getReasonPhrase(), headers);
  }
}
 
Example 8
Source File: OneFichierUploaderPlugin.java    From neembuu-uploader with GNU General Public License v3.0 5 votes vote down vote up
public static void fileUpload() throws Exception {
        HttpClient httpclient = new DefaultHttpClient();
        httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        file = new File("C:\\Documents and Settings\\dinesh\\Desktop\\FourSharedUploaderPlugin.java");
//        file = new File("e:\\dinesh.txt");
        HttpPost httppost = new HttpPost("http://upload.1fichier.com/en/upload.cgi?id=" + uid);
        if (login) {
            httppost.setHeader("Cookie", sidcookie);
        }
        MultipartEntity mpEntity = new MultipartEntity();
        ContentBody cbFile = new FileBody(file);
//        mpEntity.addPart("UPLOAD_IDENTIFIER", new StringBody(uploadid));
        mpEntity.addPart("file[]", cbFile);
        mpEntity.addPart("domain", new StringBody("0"));
        httppost.setEntity(mpEntity);
        System.out.println("Now uploading your file into 1fichier...........................");
        System.out.println("Now executing......." + httppost.getRequestLine());
        HttpResponse response = httpclient.execute(httppost);
//        HttpEntity resEntity = response.getEntity();
        System.out.println(response.getStatusLine());
        if (response.containsHeader("Location")) {
            uploadresponse = response.getFirstHeader("Location").getValue();
            System.out.println("Upload location link : " + uploadresponse);
        } else {
            throw new Exception("There might be a problem with your internet connection or server error. Please try again");
        }
    }
 
Example 9
Source File: Surrogate.java    From esigate with Apache License 2.0 5 votes vote down vote up
/**
 * Remove Surrogate-Control header or replace by its new value.
 * 
 * @param response
 *            backend HTTP response.
 * @param keepHeader
 *            should the Surrogate-Control header be forwarded to the client.
 */
private static void processSurrogateControlContent(HttpResponse response, boolean keepHeader) {
    if (!response.containsHeader(H_SURROGATE_CONTROL)) {
        return;
    }

    if (!keepHeader) {
        response.removeHeaders(H_SURROGATE_CONTROL);
        return;
    }

    MoveResponseHeader.moveHeader(response, H_X_NEXT_SURROGATE_CONTROL, H_SURROGATE_CONTROL);
}
 
Example 10
Source File: MoveResponseHeader.java    From esigate with Apache License 2.0 5 votes vote down vote up
/**
 * This method can be used directly to move an header.
 * 
 * @param response
 *            HTTP response
 * @param srcName
 *            source header name
 * @param targetName
 *            target header name
 */
public static void moveHeader(HttpResponse response, String srcName, String targetName) {
    if (response.containsHeader(srcName)) {
        LOG.info("Moving header {} to {}", srcName, targetName);

        Header[] headers = response.getHeaders(srcName);
        response.removeHeaders(targetName);
        for (Header h : headers) {
            response.addHeader(targetName, h.getValue());
        }
        response.removeHeaders(srcName);
    }
}
 
Example 11
Source File: DefaultHttpRedirectHandler.java    From android-open-project-demo with Apache License 2.0 5 votes vote down vote up
@Override
public HttpRequestBase getDirectRequest(HttpResponse response) {
    if (response.containsHeader("Location")) {
        String location = response.getFirstHeader("Location").getValue();
        HttpGet request = new HttpGet(location);
        if (response.containsHeader("Set-Cookie")) {
            String cookie = response.getFirstHeader("Set-Cookie").getValue();
            request.addHeader("Cookie", cookie);
        }
        return request;
    }
    return null;
}
 
Example 12
Source File: SimpleRestClient.java    From canvas-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
private void checkHeaders(HttpResponse httpResponse, HttpRequestBase request) {
    int statusCode = httpResponse.getStatusLine().getStatusCode();
    double rateLimitThreshold = 0.1;
    double xRateCost = 0;
    double xRateLimitRemaining = 0;

    try {
        xRateCost = Double.parseDouble(httpResponse.getFirstHeader("x-request-cost").getValue());
        xRateLimitRemaining = Double.parseDouble(httpResponse.getFirstHeader("x-rate-limit-remaining").getValue());

        //Throws a 403 with a "Rate Limit Exceeded" error message if the API throttle limit is hit.
        //See https://canvas.instructure.com/doc/api/file.throttling.html.
        if(xRateLimitRemaining < rateLimitThreshold) {
            LOG.error("Canvas API rate limit exceeded. Bucket quota: " + xRateLimitRemaining + " Cost: " + xRateCost
                    + " Threshold: " + rateLimitThreshold + " HTTP status: " + statusCode + " Requested URL: " + request.getURI());
            throw new RateLimitException(extractErrorMessageFromResponse(httpResponse), String.valueOf(request.getURI()));
        }
    } catch (NullPointerException e) {
        LOG.debug("Rate not being limited: " + e);
    }
    if (statusCode == 401) {
        //If the WWW-Authenticate header is set, it is a token problem.
        //If the header is not present, it is a user permission error.
        //See https://canvas.instructure.com/doc/api/file.oauth.html#storing-access-tokens
        if(httpResponse.containsHeader(HttpHeaders.WWW_AUTHENTICATE)) {
            LOG.debug("User's token is invalid. It might need refreshing");
            throw new InvalidOauthTokenException();
        }
        LOG.error("User is not authorized to perform this action");
        throw new UnauthorizedException();
    }
    if(statusCode == 404) {
        LOG.error("Object not found in Canvas. Requested URL: " + request.getURI());
        throw new ObjectNotFoundException(extractErrorMessageFromResponse(httpResponse), String.valueOf(request.getURI()));
    }
    // If we receive a 5xx exception, we should not wrap it in an unchecked exception for upstream clients to deal with.
    if(statusCode < 200 || (statusCode > 299 && statusCode <= 499)) {
        LOG.error("HTTP status " + statusCode + " returned from " + request.getURI());
        handleError(request, httpResponse);
    }
    //TODO Handling of 422 when the entity is malformed.
}
 
Example 13
Source File: MixerHttpClient.java    From beam-client-java with MIT License 4 votes vote down vote up
/**
 * Given a HTTP Response, check to see if a CSRF token is present, If it is we store this in the Client
 * for future requests.
 */
private void handleCSRF(HttpResponse response) {
    if (response.containsHeader(CSRF_TOKEN_HEADER)) {
        this.csrfToken = response.getHeaders(CSRF_TOKEN_HEADER)[0].getValue();
    }
}