List of usage examples for java.net HttpURLConnection getHeaderField
public String getHeaderField(int n)
From source file:com.pliu.azuremgmtsdk.BasicFilter.java
private void getTenantIdForSubscription(HttpServletRequest httpRequest) throws Exception { // figure out the tenant for the subscription String subscriptionId = httpRequest.getSession().getAttribute("subscriptionId").toString(); URL url = new URL( "https://management.azure.com/subscriptions/" + subscriptionId + "?api-version=2015-07-01"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); try {// w ww . j a v a 2 s. c o m HttpClientHelper.getResponseStringFromConn(conn, true); } catch (Exception e) { String mark = "authorization_uri="; String mark2 = "https://"; String header = conn.getHeaderField("WWW-Authenticate"); int idxbegin = header.indexOf(mark) + mark.length() + 1; idxbegin = header.indexOf(mark2, idxbegin) + mark2.length() + 1; idxbegin = header.indexOf("/", idxbegin) + 1; int idxend = header.indexOf('"', idxbegin); userTenant = header.substring(idxbegin, idxend); httpRequest.getSession().setAttribute("userTenant", userTenant); } }
From source file:org.apache.jmeter.protocol.http.control.TestHTTPMirrorThread.java
public void testCookie() throws Exception { URL url = new URL("http", "localhost", HTTP_SERVER_PORT, "/"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.addRequestProperty("X-SetCookie", "four=2*2"); conn.connect();/* www .jav a 2s . c om*/ assertEquals("four=2*2", conn.getHeaderField("Set-Cookie")); }
From source file:org.pac4j.cas.client.rest.CasRestAuthenticator.java
private String requestTicketGrantingTicket(final String username, final String password) { HttpURLConnection connection = null; try {/* w w w.j av a 2s .c o m*/ connection = HttpUtils.openPostConnection(new URL(getCasRestUrl())); final String payload = HttpUtils.encodeQueryParam(getUsernameParameter(), username) + "&" + HttpUtils.encodeQueryParam(getPasswordParameter(), password); final BufferedWriter out = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream())); out.write(payload); out.close(); final String locationHeader = connection.getHeaderField("location"); final int responseCode = connection.getResponseCode(); if (locationHeader != null && responseCode == HttpStatus.SC_CREATED) { return locationHeader.substring(locationHeader.lastIndexOf("/") + 1); } throw new TechnicalException("Ticket granting ticket request failed: " + locationHeader + " " + responseCode + HttpUtils.buildHttpErrorMessage(connection)); } catch (final IOException e) { throw new TechnicalException(e); } finally { HttpUtils.closeConnection(connection); } }
From source file:org.apache.axis2.wsdl.codegen.CodeGenerationEngine.java
/** * @param parser//from w ww . ja va 2s . c o m * @throws CodeGenerationException */ public CodeGenerationEngine(CommandLineOptionParser parser) throws CodeGenerationException { Map allOptions = parser.getAllOptions(); String wsdlUri; try { CommandLineOption option = (CommandLineOption) allOptions .get(CommandLineOptionConstants.WSDL2JavaConstants.WSDL_LOCATION_URI_OPTION); wsdlUri = option.getOptionValue(); // the redirected urls gives problems in code generation some times with jaxbri // eg. https://www.paypal.com/wsdl/PayPalSvc.wsdl // if there is a redirect url better to find it and use. if (wsdlUri.startsWith("http")) { URL url = new URL(wsdlUri); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(false); connection.getResponseCode(); String newLocation = connection.getHeaderField("Location"); if (newLocation != null) { wsdlUri = newLocation; } } configuration = new CodeGenConfiguration(allOptions); if (CommandLineOptionConstants.WSDL2JavaConstants.WSDL_VERSION_2 .equals(configuration.getWSDLVersion())) { WSDL20ToAxisServiceBuilder builder; // jibx currently does not support multiservice if ((configuration.getServiceName() != null) || (configuration.getDatabindingType().equals("jibx"))) { builder = new WSDL20ToAxisServiceBuilder(wsdlUri, configuration.getServiceName(), configuration.getPortName(), configuration.isAllPorts()); builder.setCodegen(true); configuration.addAxisService(builder.populateService()); } else { builder = new WSDL20ToAllAxisServicesBuilder(wsdlUri, configuration.getPortName()); builder.setCodegen(true); builder.setAllPorts(configuration.isAllPorts()); configuration.setAxisServices(((WSDL20ToAllAxisServicesBuilder) builder).populateAllServices()); } } else { //It'll be WSDL 1.1 Definition wsdl4jDef = readInTheWSDLFile(wsdlUri); // we save the original wsdl definition to write it to the resource folder later // this is required only if it has imports Map imports = wsdl4jDef.getImports(); if ((imports != null) && (imports.size() > 0)) { configuration.setWsdlDefinition(readInTheWSDLFile(wsdlUri)); } else { configuration.setWsdlDefinition(wsdl4jDef); } // we generate the code for one service and one port if the // user has specified them. // otherwise generate the code for every service. // TODO: find out a permanant solution for this. QName serviceQname = null; if (configuration.getServiceName() != null) { serviceQname = new QName(wsdl4jDef.getTargetNamespace(), configuration.getServiceName()); } WSDL11ToAxisServiceBuilder builder; // jibx currently does not support multiservice if ((serviceQname != null) || (configuration.getDatabindingType().equals("jibx"))) { builder = new WSDL11ToAxisServiceBuilder(wsdl4jDef, serviceQname, configuration.getPortName(), configuration.isAllPorts()); builder.setCodegen(true); configuration.addAxisService(builder.populateService()); } else { builder = new WSDL11ToAllAxisServicesBuilder(wsdl4jDef, configuration.getPortName()); builder.setCodegen(true); builder.setAllPorts(configuration.isAllPorts()); configuration.setAxisServices(((WSDL11ToAllAxisServicesBuilder) builder).populateAllServices()); } } configuration.setBaseURI(getBaseURI(wsdlUri)); } catch (AxisFault axisFault) { throw new CodeGenerationException(CodegenMessages.getMessage("engine.wsdlParsingException"), axisFault); } catch (WSDLException e) { throw new CodeGenerationException(CodegenMessages.getMessage("engine.wsdlParsingException"), e); } catch (Exception e) { throw new CodeGenerationException(CodegenMessages.getMessage("engine.wsdlParsingException"), e); } loadExtensions(); }
From source file:org.apache.olingo.fit.tecsvc.http.DerivedAndMixedTypeTestITCase.java
@Test public void queryESCompCollDerivedJson() throws Exception { URL url = new URL(SERVICE_URI + "ESCompCollDerived?$format=json"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(HttpMethod.GET.name()); connection.connect();/*w ww .j av a2 s .c om*/ assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode()); assertEquals(ContentType.JSON, ContentType.create(connection.getHeaderField(HttpHeader.CONTENT_TYPE))); final String content = IOUtils.toString(connection.getInputStream()); assertTrue(content.contains( "[{\"PropertyInt16\":32767,\"PropertyCompAno\":null,\"CollPropertyCompAno\":[{\"PropertyString\":" + "\"TEST9876\"}]},{\"PropertyInt16\":12345,\"PropertyCompAno\":{\"@odata.type\":" + "\"#olingo.odata.test1.CTBaseAno\",\"PropertyString\":\"Num111\",\"AdditionalPropString\":" + "\"Test123\"},\"CollPropertyCompAno\":[{\"@odata.type\":\"#olingo.odata.test1.CTBaseAno\"," + "\"PropertyString\":\"TEST12345\",\"AdditionalPropString\":\"Additional12345\"}," + "{\"PropertyString\":\"TESTabcd\"}]}]}")); }
From source file:org.apache.olingo.fit.tecsvc.http.BasicHttpITCase.java
@Test public void testAcceptCharset() throws Exception { URL url = new URL(SERVICE_URI); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(HttpMethod.GET.name()); connection.setRequestProperty(HttpHeader.ACCEPT, "application/json;q=0.2;odata.metadata=minimal;charset=utf-8"); connection.connect();/*w w w. j av a 2s . c o m*/ assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode()); assertEquals(ContentType.create(ContentType.JSON, ContentType.PARAMETER_CHARSET, "utf-8"), ContentType.create(connection.getHeaderField(HttpHeader.CONTENT_TYPE))); }
From source file:fr.gael.dhus.datastore.scanner.ODataScanner.java
@Override public int scan() throws InterruptedException { // Workaround: transferring 1 product. see l.50 if (this.client == null) { try {// www . j a v a 2s. co m URL url = new URL(this.uri); HttpURLConnection co = (HttpURLConnection) url.openConnection(); // HTTP Basic Authentication. String userpass = this.username + ":" + this.password; String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes())); co.setRequestProperty("Authorization", basicAuth); co.connect(); String cd = co.getHeaderField("Content-Disposition"); co.disconnect(); Matcher m = Pattern.compile(".*?filename=\"(.*?)\\.zip\".*?").matcher((cd)); if (!m.matches()) throw new Exception("filename not in header"); String filename = m.group(1); //url = new URIBuilder (url.toURI ()) // .setUserInfo (this.username, this.password).build ().toURL (); this.getScanList().add(new URLExt(url, false, filename)); } catch (Exception e) { LOGGER.error("failed to transfer " + this.uri, e); return 0; } return 1; } // The actual scan() code. int res = 0; try { // Prepare OData request, we want Products. String resource_path = new String("/Products"); Facets facets = (new Facets()).setNullable(false); Map<String, String> query_params = new HashMap<>(); long now = System.currentTimeMillis(); EdmSimpleType type = RuntimeDelegate.getEdmSimpleType(DateTime); // Filtering by ingestionDate. if (this.lastScanTime != 0L) { StringBuilder sb = new StringBuilder("IngestionDate ge "); Date l_time = new Date(this.lastScanTime); sb.append(type.valueToString(l_time, EdmLiteralKind.URI, facets)); sb.append(" and IngestionDate lt "); l_time = new Date(now); sb.append(type.valueToString(l_time, EdmLiteralKind.URI, facets)); query_params.put("$filter", sb.toString()); } else { Date l_time = new Date(now); String value = "IngestionDate lt " + type.valueToString(l_time, EdmLiteralKind.URI, facets); query_params.put("$filter", value); } // Ordering by ingestionDate. query_params.put("$orderby", "IngestionDate"); // Pagination. int page_len = 50; // TODO get this value from config. query_params.put("$top", String.valueOf(page_len)); try { for (long i = 0;; i++) { if (i != 0) query_params.put("$skip", String.valueOf(page_len * i)); ODataFeed of = this.client.readFeed(resource_path, query_params); for (ODataEntry entry : of.getEntries()) { String pdt_name = (String) entry.getProperties().get("Name"); if (this.getUserPattern() == null || this.getUserPattern().matcher(pdt_name).matches()) { String key = (String) entry.getProperties().get("Id"); URL url = new URIBuilder( this.client.getServiceRoot() + "/Products" + "('" + key + "')/$value") .setUserInfo(this.username, this.password).build().toURL(); this.getScanList().add(new URLExt(url, false, pdt_name)); res += 1; } } if (of.getEntries().size() != page_len) // End of pagination. break; } } catch (ODataException | IOException | URISyntaxException e) { LOGGER.error("Product retrieval failed", e); } this.lastScanTime = now; } catch (ODataException e) { LOGGER.error(e); } return res; }
From source file:hudson.tools.JDKInstaller.java
@SuppressWarnings("unchecked") // dom4j doesn't do generics, apparently... should probably switch to XOM private HttpURLConnection locateStage1(Platform platform, CPU cpu) throws IOException { URL url = new URL( "https://cds.sun.com/is-bin/INTERSHOP.enfinity/WFS/CDS-CDS_Developer-Site/en_US/-/USD/ViewProductDetail-Start?ProductRef=" + id);/*from www . jav a 2s. c o m*/ HttpURLConnection con = (HttpURLConnection) url.openConnection(); String cookie = con.getHeaderField("Set-Cookie"); LOGGER.fine("Cookie=" + cookie); Tidy tidy = new Tidy(); tidy.setErrout(new PrintWriter(new NullWriter())); DOMReader domReader = new DOMReader(); Document dom = domReader.read(tidy.parseDOM(con.getInputStream(), null)); Element form = null; for (Element e : (List<Element>) dom.selectNodes("//form")) { String action = e.attributeValue("action"); LOGGER.fine("Found form:" + action); if (action.contains("ViewFilteredProducts")) { form = e; break; } } con = (HttpURLConnection) new URL(form.attributeValue("action")).openConnection(); con.setRequestMethod("POST"); con.setDoOutput(true); con.setRequestProperty("Cookie", cookie); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); PrintStream os = new PrintStream(con.getOutputStream()); // select platform String primary = null, secondary = null; Element p = (Element) form.selectSingleNode(".//select[@id='dnld_platform']"); for (Element opt : (List<Element>) p.elements("option")) { String value = opt.attributeValue("value"); String vcap = value.toUpperCase(Locale.ENGLISH); if (!platform.is(vcap)) continue; switch (cpu.accept(vcap)) { case PRIMARY: primary = value; break; case SECONDARY: secondary = value; break; case UNACCEPTABLE: break; } } if (primary == null) primary = secondary; if (primary == null) throw new AbortException( "Couldn't find the right download for " + platform + " and " + cpu + " combination"); os.print(p.attributeValue("name") + '=' + primary); LOGGER.fine("Platform choice:" + primary); // select language Element l = (Element) form.selectSingleNode(".//select[@id='dnld_language']"); if (l != null) { os.print("&" + l.attributeValue("name") + "=" + l.element("option").attributeValue("value")); } // the rest for (Element e : (List<Element>) form.selectNodes(".//input")) { os.print('&'); os.print(e.attributeValue("name")); os.print('='); String value = e.attributeValue("value"); if (value == null) os.print("on"); // assume this is a checkbox else os.print(URLEncoder.encode(value, "UTF-8")); } os.close(); return con; }
From source file:io.takari.jdkget.transport.OracleWebsiteTransport.java
public boolean downloadJdk(Arch arch, JdkVersion jdkVersion, File jdkImage, IOutput output) throws IOException { String url = String.format(JDK_URL_FORMAT, jdkVersion.major, jdkVersion.revision, jdkVersion.buildNumber, jdkVersion.major, jdkVersion.revision, arch.getArch(), arch.getExtension()); output.info("Downloading " + url); // Oracle does some redirects so we have to follow a couple before we win the JDK prize URL jdkUrl;// ww w . j a va2 s . c o m int response = 0; HttpURLConnection connection; for (int retry = 0; retry < 4; retry++) { jdkUrl = new URL(url); connection = (HttpURLConnection) jdkUrl.openConnection(); connection.setRequestProperty("Cookie", OTN_COOKIE); response = connection.getResponseCode(); if (response == 200) { try (InputStream is = connection.getInputStream(); OutputStream os = new FileOutputStream(jdkImage)) { IOUtils.copy(is, os); } return true; } else if (response == 302) { url = connection.getHeaderField("Location"); } } return false; }
From source file:com.github.hexocraftapi.updater.updater.Downloader.java
/** * Download the file and save it to the updater folder. *//*from www. jav a2 s .c om*/ private boolean downloadFile() { BufferedInputStream in = null; FileOutputStream fout = null; try { // Init connection HttpURLConnection connection = (HttpURLConnection) initConnection(this.update.getDownloadUrl()); // always check HTTP response code first int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_MOVED_TEMP || responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_SEE_OTHER) { String newUrl = connection.getHeaderField("Location"); connection = (HttpURLConnection) initConnection(new URL(newUrl)); responseCode = connection.getResponseCode(); } // always check HTTP response code first if (responseCode == HttpURLConnection.HTTP_OK) { String fileName = ""; String fileURL = this.update.getDownloadUrl().toString(); String disposition = connection.getHeaderField("Content-Disposition"); String contentType = connection.getContentType(); int fileLength = connection.getContentLength(); // extracts file name from header field if (disposition != null) { int index = disposition.indexOf("filename="); if (index > 0) fileName = disposition.substring(index + 10, disposition.length() - 1); } // extracts file name from URL else fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1, fileURL.length()); // opens input stream from the HTTP connection in = new BufferedInputStream(connection.getInputStream()); // opens an output stream to save into file fout = new FileOutputStream(new File(this.updateFolder, fileName)); log(Level.INFO, "About to download a new update: " + this.update.getVersion().toString()); final byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead; while ((bytesRead = in.read(buffer, 0, BUFFER_SIZE)) != -1) fout.write(buffer, 0, bytesRead); log(Level.INFO, "File downloaded: " + fileName); } } catch (Exception ex) { log(Level.WARNING, "The auto-updater tried to download a new update, but was unsuccessful."); return false; } finally { try { if (in != null) in.close(); } catch (final IOException ex) { log(Level.SEVERE, null); return false; } try { if (fout != null) fout.close(); } catch (final IOException ex) { log(Level.SEVERE, null); return false; } return true; } }