List of usage examples for org.apache.http.client.methods CloseableHttpResponse getFirstHeader
Header getFirstHeader(String str);
From source file:org.commonjava.maven.galley.transport.htcli.util.HttpUtil.java
public static long getContentLength(CloseableHttpResponse response) { if (response == null) { return -1; }/*ww w .jav a2 s .c o m*/ Header header = response.getFirstHeader(CONTENT_LENGTH); return header == null ? 0 : Long.parseLong(header.getValue()); }
From source file:utils.TestUtils.java
public static String httpGetHeader(String url, String header) throws Exception { CloseableHttpResponse resp = null; try {/*from w w w . java 2 s . c om*/ HttpGet get = new HttpGet(url); resp = HTTP.execute(get); return resp.getFirstHeader(header).getValue(); } finally { closeQuietly(resp); } }
From source file:shootersubdownloader.Shootersubdownloader.java
private static void down(File f) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); String url = String.format("https://www.shooter.cn/api/subapi.php?filehash=%s&pathinfo=%s&format=json", computefilehash(f), f.getName()); System.out.println(url);/*from www.j a v a 2s . c o m*/ HttpGet request = new HttpGet(url); CloseableHttpResponse r = httpclient.execute(request); System.out.println(r.getStatusLine()); HttpEntity e = r.getEntity(); String s = EntityUtils.toString(e); System.out.println(s); JSONArray json = JSONArray.fromObject(s); // JSONObject json = JSONObject.fromObject(s); System.out.println(json.size()); for (int i = 0; i < json.size(); i++) { System.out.println(i); JSONObject obj = json.getJSONObject(i); JSONArray fs = obj.getJSONArray("Files"); String downurl = fs.getJSONObject(0).getString("Link"); HttpGet r2 = new HttpGet(downurl); CloseableHttpResponse res2 = httpclient.execute(r2); // Header[] headers = res2.getAllHeaders(); // for(Header h:headers){ // System.out.println(h.getName()); // System.out.println(h.getValue()); // } Header header = res2.getFirstHeader("Content-Disposition"); String sig = "filename="; String v = header.getValue(); String fn = v.substring(v.indexOf(sig) + sig.length()); HttpEntity e2 = res2.getEntity(); File outf = new File(fn); FileOutputStream fos = new FileOutputStream(outf); e2.writeTo(fos); System.out.println(filecharsetdetect.FileCharsetDetect.detect(outf)); // res2.getEntity().writeTo(new FileOutputStream(fn)); System.out.println(fn); res2.close(); } r.close(); httpclient.close(); }
From source file:com.linecorp.armeria.server.http.file.HttpFileServiceTest.java
private static void assert404NotFound(CloseableHttpResponse res) { assertStatusLine(res, "HTTP/1.1 404 Not Found"); // Ensure that the 'Last-Modified' header does not exist. assertThat(res.getFirstHeader(HttpHeaders.LAST_MODIFIED), is(nullValue())); }
From source file:com.linecorp.armeria.server.http.file.HttpFileServiceTest.java
private static void assert304NotModified(CloseableHttpResponse res, String expectedLastModified) { assertStatusLine(res, "HTTP/1.1 304 Not Modified"); // Ensure that the 'Last-Modified' header did not change. assertThat(res.getFirstHeader(HttpHeaders.LAST_MODIFIED).getValue(), is(expectedLastModified)); // Ensure that the content does not exist. assertThat(res.getEntity(), is(nullValue())); }
From source file:org.darkware.wpman.wpcli.WPCLI.java
/** * Update the local WP-CLI tool to the most recent version. *//*from w w w . j av a 2 s . c o m*/ public static void update() { try { WPManager.log.info("Downloading new version of WP-CLI."); CloseableHttpClient httpclient = HttpClients.createDefault(); URI pharURI = new URIBuilder().setScheme("http").setHost("raw.githubusercontent.com") .setPath("/wp-cli/builds/gh-pages/phar/wp-cli.phar").build(); WPManager.log.info("Downloading from: {}", pharURI); HttpGet downloadRequest = new HttpGet(pharURI); CloseableHttpResponse response = httpclient.execute(downloadRequest); WPManager.log.info("Download response: {}", response.getStatusLine()); WPManager.log.info("Download content type: {}", response.getFirstHeader("Content-Type").getValue()); FileChannel wpcliFile = FileChannel.open(WPCLI.toolPath, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE); response.getEntity().writeTo(Channels.newOutputStream(wpcliFile)); wpcliFile.close(); Set<PosixFilePermission> wpcliPerms = new HashSet<>(); wpcliPerms.add(PosixFilePermission.OWNER_READ); wpcliPerms.add(PosixFilePermission.OWNER_WRITE); wpcliPerms.add(PosixFilePermission.OWNER_EXECUTE); wpcliPerms.add(PosixFilePermission.GROUP_READ); wpcliPerms.add(PosixFilePermission.GROUP_EXECUTE); Files.setPosixFilePermissions(WPCLI.toolPath, wpcliPerms); } catch (URISyntaxException e) { WPManager.log.error("Failure building URL for WPCLI download.", e); System.exit(1); } catch (IOException e) { WPManager.log.error("Error while downloading WPCLI client.", e); e.printStackTrace(); System.exit(1); } }
From source file:com.linecorp.armeria.server.http.file.HttpFileServiceTest.java
private static String assert200Ok(CloseableHttpResponse res, String expectedContentType, String expectedContent) throws Exception { assertStatusLine(res, "HTTP/1.1 200 OK"); // Ensure that the 'Last-Modified' header exists and is well-formed. final String lastModified; assertThat(res.containsHeader(HttpHeaders.LAST_MODIFIED), is(true)); lastModified = res.getFirstHeader(HttpHeaders.LAST_MODIFIED).getValue(); HttpHeaderDateFormat.get().parse(lastModified); // Ensure the content and its type are correct. assertThat(EntityUtils.toString(res.getEntity()), is(expectedContent)); if (expectedContentType != null) { assertThat(res.containsHeader(HttpHeaders.CONTENT_TYPE), is(true)); assertThat(res.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue(), startsWith(expectedContentType)); } else {/* w w w . ja va2 s .c om*/ assertThat(res.containsHeader(HttpHeaders.CONTENT_TYPE), is(false)); } return lastModified; }
From source file:com.linkedin.pinot.common.utils.FileUploadDownloadClient.java
private static String getErrorMessage(HttpUriRequest request, CloseableHttpResponse response) { String controllerHost = null; String controllerVersion = null; if (response.containsHeader(CommonConstants.Controller.HOST_HTTP_HEADER)) { controllerHost = response.getFirstHeader(CommonConstants.Controller.HOST_HTTP_HEADER).getValue(); controllerVersion = response.getFirstHeader(CommonConstants.Controller.VERSION_HTTP_HEADER).getValue(); }// w ww. j a va 2 s . co m StatusLine statusLine = response.getStatusLine(); String reason; try { reason = new JSONObject(EntityUtils.toString(response.getEntity())).getString("error"); } catch (Exception e) { reason = "Failed to get reason"; } String errorMessage = String.format( "Got error status code: %d (%s) with reason: \"%s\" while sending request: %s", statusLine.getStatusCode(), statusLine.getReasonPhrase(), reason, request.getURI()); if (controllerHost != null) { errorMessage = String.format("%s to controller: %s, version: %s", errorMessage, controllerHost, controllerVersion); } return errorMessage; }
From source file:com.ibm.team.build.internal.hjplugin.util.HttpUtils.java
/** * Post a login form to the server when authentication was required by the previous request * @param httpClient The httpClient to use for the requests * @param httpContext httpContext with it's own cookie store for use with the singleton HTTP_CLIENT * Not <code>null</code>// www . j a va2 s .co m * @param serverURI The RTC server * @param userId The userId to authenticate as * @param password The password to authenticate with * @param timeout The timeout period for the connection (in seconds) * @param listener The listener to report errors to. May be * <code>null</code> * @throws IOException Thrown if things go wrong * @throws InvalidCredentialsException if authentication fails */ private static CloseableHttpResponse handleFormBasedChallenge(CloseableHttpClient httpClient, HttpClientContext httpContext, String serverURI, String userId, String password, int timeout, TaskListener listener) throws IOException, InvalidCredentialsException { // The server requires an authentication: Create the login form String fullURI = getFullURI(serverURI, "j_security_check"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("j_username", userId)); //$NON-NLS-1$ nvps.add(new BasicNameValuePair("j_password", password)); //$NON-NLS-1$ HttpPost formPost = getPOST(fullURI, timeout); //$NON-NLS-1$ formPost.setEntity(new UrlEncodedFormEntity(nvps, UTF_8)); // The client submits the login form LOGGER.finer("POST: " + formPost.getURI()); //$NON-NLS-1$ CloseableHttpResponse formResponse = httpClient.execute(formPost, httpContext); int statusCode = formResponse.getStatusLine().getStatusCode(); Header header = formResponse.getFirstHeader(FORM_AUTHREQUIRED_HEADER); // check to see if the authentication was successful if (statusCode / 100 == 2 && (header != null) && (AUTHFAILED_HEADER_VALUE.equals(header.getValue()))) { closeResponse(formResponse); throw new InvalidCredentialsException(Messages.HttpUtils_authentication_failed(userId, serverURI)); } return formResponse; }
From source file:vn.vndirect.form.model.SendURIModel.java
public SendURIModel(String image, String filenameKH, String filenameKN) { try {/*from w w w .j a v a 2 s .c o m*/ CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost post = new HttpPost(URItoGMC + "?ImgName=" + image + "&csvKH=" + "KH" + filenameKH + ".csv" + "&csvKN=" + "KN" + filenameKN + ".csv"); post.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded;charset=" + "UTF-16"); //post.setEntity(new UrlEncodedFormEntity(nvps)); CloseableHttpResponse response = httpclient.execute(post); System.out.println("Header " + response.getFirstHeader("Location")); } catch (Exception e) { } }