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

The following examples show how to use org.apache.http.HttpResponse#getFirstHeader() . 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: OtherUtils.java    From BigApp_Discuz_Android with Apache License 2.0 6 votes vote down vote up
public static String getFileNameFromHttpResponse(final HttpResponse response) {
    if (response == null) return null;
    String result = null;
    Header header = response.getFirstHeader("Content-Disposition");
    if (header != null) {
        for (HeaderElement element : header.getElements()) {
            NameValuePair fileNamePair = element.getParameterByName("filename");
            if (fileNamePair != null) {
                result = fileNamePair.getValue();
                // try to get correct encoding str
                result = CharsetUtils.toCharset(result, HTTP.UTF_8, result.length());
                break;
            }
        }
    }
    return result;
}
 
Example 2
Source File: CacheHeaderTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@SuppressForbidden(reason = "Needs currentTimeMillis to check against expiry headers from Solr")
protected void checkVetoHeaders(HttpResponse response, boolean checkExpires) throws Exception {
  Header head = response.getFirstHeader("Cache-Control");
  assertNotNull("We got no Cache-Control header", head);
  assertTrue("We got no no-cache in the Cache-Control header ["+head+"]", head.getValue().contains("no-cache"));
  assertTrue("We got no no-store in the Cache-Control header ["+head+"]", head.getValue().contains("no-store"));

  head = response.getFirstHeader("Pragma");
  assertNotNull("We got no Pragma header", head);
  assertEquals("no-cache", head.getValue());

  if (checkExpires) {
    head = response.getFirstHeader("Expires");
    assertNotNull("We got no Expires header:" + Arrays.asList(response.getAllHeaders()), head);
    Date d = DateUtils.parseDate(head.getValue());
    assertTrue("We got no Expires header far in the past", System
        .currentTimeMillis()
        - d.getTime() > 100000);
  }
}
 
Example 3
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 4
Source File: DigitalOceanClient.java    From digitalocean-api-java with MIT License 6 votes vote down vote up
/** Easy method for HTTP header values (first/last) */
private String getSimpleHeaderValue(String header, HttpResponse httpResponse, boolean first) {
  if (StringUtils.isBlank(header)) {
    return StringUtils.EMPTY;
  }

  Header h;
  if (first) {
    h = httpResponse.getFirstHeader(header);
  } else {
    h = httpResponse.getLastHeader(header);
  }
  if (h == null) {
    return null;
  }
  return h.getValue();
}
 
Example 5
Source File: Http4FileContentInfoFactory.java    From commons-vfs with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public FileContentInfo create(final FileContent fileContent) throws FileSystemException {
    String contentMimeType = null;
    String contentCharset = null;

    try (final Http4FileObject<Http4FileSystem> http4File = (Http4FileObject<Http4FileSystem>) FileObjectUtils
            .getAbstractFileObject(fileContent.getFile())) {
        final HttpResponse lastHeadResponse = http4File.getLastHeadResponse();

        final Header header = lastHeadResponse.getFirstHeader(HTTP.CONTENT_TYPE);

        if (header != null) {
            final ContentType contentType = ContentType.parse(header.getValue());
            contentMimeType = contentType.getMimeType();

            if (contentType.getCharset() != null) {
                contentCharset = contentType.getCharset().name();
            }
        }

        return new DefaultFileContentInfo(contentMimeType, contentCharset);
    } catch (final IOException e) {
        throw new FileSystemException(e);
    }
}
 
Example 6
Source File: DownloadThread.java    From Alite with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Handle a 3xx redirect status.
 */
private void handleRedirect(State state, HttpResponse response, int statusCode)
        throws StopRequest, RetryDownload {
    if (Constants.LOGVV) {
        Log.v(Constants.TAG, "got HTTP redirect " + statusCode);
    }
    if (state.mRedirectCount >= Constants.MAX_REDIRECTS) {
        throw new StopRequest(DownloaderService.STATUS_TOO_MANY_REDIRECTS, "too many redirects");
    }
    Header header = response.getFirstHeader("Location");
    if (header == null) {
        return;
    }
    if (Constants.LOGVV) {
        Log.v(Constants.TAG, "Location :" + header.getValue());
    }

    String newUri;
    try {
        newUri = new URI(mInfo.mUri).resolve(new URI(header.getValue())).toString();
    } catch (URISyntaxException ex) {
        if (Constants.LOGV) {
            Log.d(Constants.TAG, "Couldn't resolve redirect URI " + header.getValue()
                    + " for " + mInfo.mUri);
        }
        throw new StopRequest(DownloaderService.STATUS_HTTP_DATA_ERROR,
                "Couldn't resolve redirect URI");
    }
    ++state.mRedirectCount;
    state.mRequestUri = newUri;
    throw new RetryDownload();
}
 
Example 7
Source File: ResponseCachingPolicy.java    From apigee-android-sdk with Apache License 2.0 5 votes vote down vote up
protected boolean isExplicitlyCacheable(HttpResponse response) {
	if (response.getFirstHeader(HeaderConstants.EXPIRES) != null)
		return true;
	String[] cacheableParams = { "max-age", "s-maxage", "must-revalidate",
			"proxy-revalidate", "public" };
	return hasCacheControlParameterFrom(response, cacheableParams);
}
 
Example 8
Source File: DataServiceVersionTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testDataServiceVersionCase() throws Exception {
  HttpResponse response = callUri("Employees");
  Header header = response.getFirstHeader("dataserviceversion");
  assertNotNull(header);
  assertEquals(ODataServiceVersion.V20, header.getValue());

  checkVersion(response, ODataServiceVersion.V20);
}
 
Example 9
Source File: ContentNegotiationDollarFormatTest.java    From cloud-odata-java with Apache License 2.0 5 votes vote down vote up
@Test
public void atomFormatForServiceDocument() throws Exception {
  final HttpResponse response = executeGetRequest("?$format=atom");

  final String responseEntity = StringHelper.httpEntityToString(response.getEntity());
  assertEquals("Test passed.", responseEntity);
  assertEquals(HttpStatusCodes.OK.getStatusCode(), response.getStatusLine().getStatusCode());

  final Header header = response.getFirstHeader(HttpHeaders.CONTENT_TYPE);
  assertEquals(HttpContentType.APPLICATION_ATOM_SVC_UTF8, header.getValue());
}
 
Example 10
Source File: HttpResponseResource.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private static HashValue getSha1(HttpResponse response, String etag) {
    Header sha1Header = response.getFirstHeader("X-Checksum-Sha1");
    if (sha1Header != null) {
        return new HashValue(sha1Header.getValue());    
    }

    // Nexus uses sha1 etags, with a constant prefix
    // e.g {SHA1{b8ad5573a5e9eba7d48ed77a48ad098e3ec2590b}}
    if (etag != null && etag.startsWith("{SHA1{")) {
        String hash = etag.substring(6, etag.length() - 2);
        return new HashValue(hash);
    }

    return null;
}
 
Example 11
Source File: DownloadThread.java    From Alite with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Handle a 503 Service Unavailable status by processing the Retry-After
 * header.
 */
private void handleServiceUnavailable(State state, HttpResponse response) throws StopRequest {
    if (Constants.LOGVV) {
        Log.v(Constants.TAG, "got HTTP response code 503");
    }
    state.mCountRetry = true;
    Header header = response.getFirstHeader("Retry-After");
    if (header != null) {
        try {
            if (Constants.LOGVV) {
                Log.v(Constants.TAG, "Retry-After :" + header.getValue());
            }
            state.mRetryAfter = Integer.parseInt(header.getValue());
            if (state.mRetryAfter < 0) {
                state.mRetryAfter = 0;
            } else {
                if (state.mRetryAfter < Constants.MIN_RETRY_AFTER) {
                    state.mRetryAfter = Constants.MIN_RETRY_AFTER;
                } else if (state.mRetryAfter > Constants.MAX_RETRY_AFTER) {
                    state.mRetryAfter = Constants.MAX_RETRY_AFTER;
                }
                state.mRetryAfter += Helpers.sRandom.nextInt(Constants.MIN_RETRY_AFTER + 1);
                state.mRetryAfter *= 1000;
            }
        } catch (NumberFormatException ex) {
            // ignored - retryAfter stays 0 in this case.
        }
    }
    throw new StopRequest(DownloaderService.STATUS_WAITING_TO_RETRY,
            "got 503 Service Unavailable, will retry later");
}
 
Example 12
Source File: TraceeInterceptorIT.java    From tracee with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void whenResponseIsCommitedWeShouldReceiveInitValues() throws IOException {
	final HttpResponse response = get("closeResponse", "initialVal=0815");
	assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
	final Header traceeResponseHeader = response.getFirstHeader(TPIC_HEADER);
	assertThat(traceeResponseHeader, notNullValue());
	assertThat(traceeResponseHeader.getValue(), containsString("initialVal=0815"));
	assertThat(traceeResponseHeader.getValue(), not(containsString("initialVal=laterValue321")));
}
 
Example 13
Source File: ContentNegotiationDollarFormatTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Test
public void atomFormatForServiceDocument() throws Exception {
  final HttpResponse response = executeGetRequest("?$format=atom");

  final String responseEntity = StringHelper.httpEntityToString(response.getEntity());
  assertEquals("Test passed.", responseEntity);
  assertEquals(HttpStatusCodes.OK.getStatusCode(), response.getStatusLine().getStatusCode());

  final Header header = response.getFirstHeader(HttpHeaders.CONTENT_TYPE);
  assertEquals(HttpContentType.APPLICATION_ATOM_SVC_UTF8, header.getValue());
}
 
Example 14
Source File: ExchangeDavRequest.java    From davmail with GNU General Public License v2.0 4 votes vote down vote up
@Override
public List<MultiStatusResponse> handleResponse(HttpResponse response) {
    this.response = response;
    Header contentTypeHeader = response.getFirstHeader("Content-Type");
    if (contentTypeHeader != null && "text/xml".equals(contentTypeHeader.getValue())) {
        responses = new ArrayList<>();
        XMLStreamReader reader;
        try {
            reader = XMLStreamUtil.createXMLStreamReader(new FilterInputStream(response.getEntity().getContent()) {
                final byte[] lastbytes = new byte[3];

                @Override
                public int read(byte[] bytes, int off, int len) throws IOException {
                    int count = in.read(bytes, off, len);
                    // patch invalid element name
                    for (int i = 0; i < count; i++) {
                        byte currentByte = bytes[off + i];
                        if ((lastbytes[0] == '<') && (currentByte >= '0' && currentByte <= '9')) {
                            // move invalid first tag char to valid range
                            bytes[off + i] = (byte) (currentByte + 49);
                        }
                        lastbytes[0] = lastbytes[1];
                        lastbytes[1] = lastbytes[2];
                        lastbytes[2] = currentByte;
                    }
                    return count;
                }

            });
            while (reader.hasNext()) {
                reader.next();
                if (XMLStreamUtil.isStartTag(reader, "response")) {
                    handleResponse(reader);
                }
            }

        } catch (IOException | XMLStreamException e) {
            LOGGER.error("Error while parsing soap response: " + e, e);
        }
    }
    return responses;
}
 
Example 15
Source File: HttpClientHandler.java    From ant-ivy with Apache License 2.0 4 votes vote down vote up
private Header getContentEncoding(final HttpResponse response) {
    return response.getFirstHeader("Content-Encoding");
}
 
Example 16
Source File: NoCacheHeaderTest.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Override
protected void doETag(String method) throws Exception {
  HttpRequestBase get = getSelectMethod(method);
  HttpResponse response = getClient().execute(get);
  checkResponseBody(method, response);

  assertEquals("Got no response code 200 in initial request", 200, response
      .getStatusLine().getStatusCode());

  Header head = response.getFirstHeader("ETag");
  assertNull("We got an ETag in the response", head);

  // If-None-Match tests
  // we set a non matching ETag
  get = getSelectMethod(method);
  get.addHeader("If-None-Match", "\"xyz123456\"");
  response = getClient().execute(get);
  checkResponseBody(method, response);
  assertEquals(
      "If-None-Match: Got no response code 200 in response to non matching ETag",
      200, response.getStatusLine().getStatusCode());

  // we now set the special star ETag
  get = getSelectMethod(method);
  get.addHeader("If-None-Match", "*");
  response = getClient().execute(get);
  checkResponseBody(method, response);
  assertEquals("If-None-Match: Got no response 200 for star ETag", 200,
      response.getStatusLine().getStatusCode());

  // If-Match tests
  // we set a non matching ETag
  get = getSelectMethod(method);
  get.addHeader("If-Match", "\"xyz123456\"");
  response = getClient().execute(get);
  checkResponseBody(method, response);
  assertEquals(
      "If-Match: Got no response code 200 in response to non matching ETag",
      200, response.getStatusLine().getStatusCode());

  // now we set the special star ETag
  get = getSelectMethod(method);
  get.addHeader("If-Match", "*");
  response = getClient().execute(get);
  checkResponseBody(method, response);
  assertEquals("If-Match: Got no response 200 to star ETag", 200, response
      .getStatusLine().getStatusCode());
}
 
Example 17
Source File: NetloadUploaderPlugin.java    From neembuu-uploader with GNU General Public License v3.0 4 votes vote down vote up
private static void fileUpload() throws Exception {
    
    
    file = new File("C:\\Documents and Settings\\dinesh\\Desktop\\NU.txt");
    
    HttpClient httpclient = new DefaultHttpClient();
    
    HttpPost httppost = new HttpPost(postURL);
    if (login) {
        httppost.setHeader("Cookie", usercookie);
    }
    
    MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    ContentBody cbFile = new FileBody(file);
    if (login) {
        mpEntity.addPart("upload_hash", new StringBody(upload_hash));
    } 
    mpEntity.addPart("file", cbFile);
    httppost.setEntity(mpEntity);
    System.out.println("executing request " + httppost.getRequestLine());
    System.out.println("Now uploading your file into netload");
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();
    
    
    System.out.println(response.getStatusLine());
    Header firstHeader = response.getFirstHeader("Location");
    System.out.println(firstHeader.getValue());
    uploadresponse = getData(firstHeader.getValue());
    System.out.println("Upload response : " + uploadresponse);
    downloadlink = parseResponse(uploadresponse, "The download link is: <br/>", "\" target=\"_blank\">");
    downloadlink = downloadlink.substring(downloadlink.indexOf("href=\""));
    downloadlink = downloadlink.replace("href=\"", "");
    System.out.println("download link : " + downloadlink);
    deletelink = parseResponse(uploadresponse, "The deletion link is: <br/>", "\" target=\"_blank\">");
    deletelink = deletelink.substring(deletelink.indexOf("href=\""));
    deletelink = deletelink.replace("href=\"", "");
    System.out.println("delete link : " + deletelink);
    httpclient.getConnectionManager().shutdown();
    
}
 
Example 18
Source File: CacheHeaderTest.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Override
protected void doLastModified(String method) throws Exception {
  // We do a first request to get the last modified
  // This must result in a 200 OK response
  HttpRequestBase get = getSelectMethod(method);
  HttpResponse response = getClient().execute(get);
  checkResponseBody(method, response);

  assertEquals("Got no response code 200 in initial request", 200, response.
      getStatusLine().getStatusCode());

  Header head = response.getFirstHeader("Last-Modified");
  assertNotNull("We got no Last-Modified header", head);

  Date lastModified = DateUtils.parseDate(head.getValue());

  // If-Modified-Since tests
  get = getSelectMethod(method);
  get.addHeader("If-Modified-Since", DateUtils.formatDate(new Date()));

  response = getClient().execute(get);
  checkResponseBody(method, response);
  assertEquals("Expected 304 NotModified response with current date", 304,
      response.getStatusLine().getStatusCode());

  get = getSelectMethod(method);
  get.addHeader("If-Modified-Since", DateUtils.formatDate(new Date(
      lastModified.getTime() - 10000)));
  response = getClient().execute(get);
  checkResponseBody(method, response);
  assertEquals("Expected 200 OK response with If-Modified-Since in the past",
      200, response.getStatusLine().getStatusCode());

  // If-Unmodified-Since tests
  get = getSelectMethod(method);
  get.addHeader("If-Unmodified-Since", DateUtils.formatDate(new Date(
      lastModified.getTime() - 10000)));

  response = getClient().execute(get);
  checkResponseBody(method, response);
  assertEquals(
      "Expected 412 Precondition failed with If-Unmodified-Since in the past",
      412, response.getStatusLine().getStatusCode());

  get = getSelectMethod(method);
  get.addHeader("If-Unmodified-Since", DateUtils
          .formatDate(new Date()));
  response = getClient().execute(get);
  checkResponseBody(method, response);
  assertEquals(
      "Expected 200 OK response with If-Unmodified-Since and current date",
      200, response.getStatusLine().getStatusCode());
}
 
Example 19
Source File: HttpClientAdapter.java    From davmail with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Test if the response is gzip encoded
 *
 * @param response http response
 * @return true if response is gzip encoded
 */
public static boolean isGzipEncoded(HttpResponse response) {
    Header header = response.getFirstHeader("Content-Encoding");
    return header != null && "gzip".equals(header.getValue());
}
 
Example 20
Source File: HttpComponentsHttpInvokerRequestExecutor.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Determine whether the given response indicates a GZIP response.
 * <p>The default implementation checks whether the HTTP "Content-Encoding"
 * header contains "gzip" (in any casing).
 * @param httpResponse the resulting HttpResponse to check
 * @return whether the given response indicates a GZIP response
 */
protected boolean isGzipResponse(HttpResponse httpResponse) {
	Header encodingHeader = httpResponse.getFirstHeader(HTTP_HEADER_CONTENT_ENCODING);
	return (encodingHeader != null && encodingHeader.getValue() != null &&
			encodingHeader.getValue().toLowerCase().contains(ENCODING_GZIP));
}