List of usage examples for java.net URLConnection setRequestProperty
public void setRequestProperty(String key, String value)
From source file:com.jaspersoft.jrx.query.JRXPathQueryExecuter.java
private Document getDocumentFromUrl(Map<String, ? extends JRValueParameter> parametersMap) throws Exception { // Get the url... String urlString = (String) getParameterValue(JRXPathQueryExecuterFactory.XML_URL); // add GET parameters to the urlString... Iterator<String> i = parametersMap.keySet().iterator(); String div = "?"; URL url = new URL(urlString); if (url.getQuery() != null) div = "&"; while (i.hasNext()) { String keyName = "" + i.next(); if (keyName.startsWith("XML_GET_PARAM_")) { String paramName = keyName.substring("XML_GET_PARAM_".length()); String value = (String) getParameterValue(keyName); urlString += div + URLEncoder.encode(paramName, "UTF-8") + "=" + URLEncoder.encode(value, "UTF-8"); div = "&"; }//w ww .j a v a 2 s. c o m } url = new URL(urlString); if (url.getProtocol().toLowerCase().equals("file")) { // do nothing return JRXmlUtils.parse(url.openStream()); } else if (url.getProtocol().toLowerCase().equals("http") || url.getProtocol().toLowerCase().equals("https")) { String username = (String) getParameterValue(JRXPathQueryExecuterFactory.XML_USERNAME); String password = (String) getParameterValue(JRXPathQueryExecuterFactory.XML_PASSWORD); if (url.getProtocol().toLowerCase().equals("https")) { JRPropertiesUtil dPROP = PropertiesHelper.DPROP; String socketFactory = dPROP .getProperty("net.sf.jasperreports.query.executer.factory.xPath.DefaultSSLSocketFactory"); if (socketFactory == null) { socketFactory = dPROP.getProperty( "net.sf.jasperreports.query.executer.factory.XPath.DefaultSSLSocketFactory"); } if (socketFactory != null) { // setSSLSocketFactory HttpsURLConnection.setDefaultSSLSocketFactory( (SSLSocketFactory) Class.forName(socketFactory).newInstance()); } else { log.debug("No SSLSocketFactory defined, using default"); } String hostnameVerifyer = dPROP .getProperty("net.sf.jasperreports.query.executer.factory.xPath.DefaultHostnameVerifier"); if (hostnameVerifyer == null) { hostnameVerifyer = dPROP.getProperty( "net.sf.jasperreports.query.executer.factory.XPath.DefaultHostnameVerifier"); } if (hostnameVerifyer != null) { // setSSLSocketFactory HttpsURLConnection.setDefaultHostnameVerifier( (HostnameVerifier) Class.forName(hostnameVerifyer).newInstance()); } else { log.debug("No HostnameVerifier defined, using default"); } } URLConnection conn = url.openConnection(); if (username != null && username.length() > 0 && password != null) { ByteArrayInputStream bytesIn = new ByteArrayInputStream((username + ":" + password).getBytes()); ByteArrayOutputStream dataOut = new ByteArrayOutputStream(); Base64Encoder enc = new Base64Encoder(bytesIn, dataOut); enc.process(); String encoding = dataOut.toString(); conn.setRequestProperty("Authorization", "Basic " + encoding); } // add POST parameters to the urlString... i = parametersMap.keySet().iterator(); String data = ""; div = ""; while (i.hasNext()) { String keyName = "" + i.next(); if (keyName.startsWith("XML_POST_PARAM_")) { String paramName = keyName.substring("XML_POST_PARAM_".length()); String value = (String) getParameterValue(keyName); data += div + URLEncoder.encode(paramName, "UTF-8") + "=" + URLEncoder.encode(value, "UTF-8"); div = "&"; } } conn.setDoOutput(true); if (data.length() > 0) { conn.setDoInput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); } try { return XMLUtils.parseNoValidation(conn.getInputStream()); } catch (SAXException e) { throw new JRException("Failed to parse the xml document", e); } catch (IOException e) { throw new JRException("Failed to parse the xml document", e); } catch (ParserConfigurationException e) { throw new JRException("Failed to create a document builder factory", e); } // return JRXmlUtils.parse(conn.getInputStream()); } else { throw new JRException("URL protocol not supported"); } }
From source file:com.upnext.blekit.util.http.HttpClient.java
public <T> Response<T> fetchResponse(Class<T> clazz, String path, Map<String, String> params, String httpMethod, String payload, String payloadContentType) { try {/*w w w . ja va 2s . co m*/ String fullUrl = urlWithParams(path != null ? url + path : url, params); L.d("[" + httpMethod + "] " + fullUrl); final URLConnection connection = new URL(fullUrl).openConnection(); if (connection instanceof HttpURLConnection) { final HttpURLConnection httpConnection = (HttpURLConnection) connection; httpConnection.setDoInput(true); if (httpMethod != null) { httpConnection.setRequestMethod(httpMethod); if (httpMethod.equals("POST")) { connection.setDoOutput(true); // Triggers POST. connection.setRequestProperty("Accept-Charset", "UTF-8"); connection.setRequestProperty("Content-Type", payloadContentType); } } else { httpConnection.setRequestMethod(params != null ? "POST" : "GET"); } httpConnection.addRequestProperty("Accept", "application/json"); httpConnection.connect(); if (payload != null) { OutputStream outputStream = httpConnection.getOutputStream(); try { if (LOG_RESPONSE) { L.d("[payload] " + payload); } OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8"); writer.write(payload); writer.close(); } finally { outputStream.close(); } } InputStream input = null; try { input = connection.getInputStream(); } catch (IOException e) { // workaround for Android HttpURLConnection ( IOException is thrown for 40x error codes ). final int statusCode = httpConnection.getResponseCode(); if (statusCode == -1) throw e; return new Response<T>(Error.httpError(httpConnection.getResponseCode())); } final int statusCode = httpConnection.getResponseCode(); L.d("statusCode " + statusCode); if (statusCode == HttpURLConnection.HTTP_OK || statusCode == HttpURLConnection.HTTP_CREATED) { try { T value = null; if (clazz != Void.class) { if (LOG_RESPONSE || clazz == String.class) { StringBuilder sb = new StringBuilder(); BufferedReader br = new BufferedReader(new InputStreamReader(input)); String read = br.readLine(); while (read != null) { sb.append(read); read = br.readLine(); } String response = sb.toString(); if (LOG_RESPONSE) { L.d("response " + response); } if (clazz == String.class) { value = (T) response; } else { value = (T) objectMapper.readValue(response, clazz); } } else { value = (T) objectMapper.readValue(input, clazz); } } return new Response<T>(value); } catch (JsonMappingException e) { return new Response<T>(Error.serlizerError(e)); } catch (JsonParseException e) { return new Response<T>(Error.serlizerError(e)); } } else if (statusCode == HttpURLConnection.HTTP_NO_CONTENT) { try { T def = clazz.newInstance(); if (LOG_RESPONSE) { L.d("statusCode == HttpURLConnection.HTTP_NO_CONTENT"); } return new Response<T>(def); } catch (InstantiationException e) { return new Response<T>(Error.ioError(e)); } catch (IllegalAccessException e) { return new Response<T>(Error.ioError(e)); } } else { if (LOG_RESPONSE) { L.d("error, statusCode " + statusCode); } return new Response<T>(Error.httpError(statusCode)); } } return new Response<T>(Error.ioError(new Exception("Url is not a http link"))); } catch (IOException e) { if (LOG_RESPONSE) { L.d("error, ioError " + e); } return new Response<T>(Error.ioError(e)); } }
From source file:org.apache.fop.apps.FOURIResolver.java
/** * This is a convenience method for users who want to override * updateURLConnection for HTTP basic authentication. Simply call it using * the right username and password./* w w w.j a v a 2s .c om*/ * * @param connection * the URLConnection to set up for HTTP basic authentication * @param username * the username * @param password * the password */ protected void applyHttpBasicAuthentication(URLConnection connection, String username, String password) { String combined = username + ":" + password; try { ByteArrayOutputStream baout = new ByteArrayOutputStream(combined.length() * 2); Base64EncodeStream base64 = new Base64EncodeStream(baout); // TODO Not sure what charset/encoding can be used with basic // authentication base64.write(combined.getBytes("UTF-8")); base64.close(); connection.setRequestProperty("Authorization", "Basic " + new String(baout.toByteArray(), "UTF-8")); } catch (IOException e) { // won't happen. We're operating in-memory. throw new RuntimeException("Error during base64 encodation of username/password"); } }
From source file:io.hummer.util.ws.WebServiceClient.java
private InvocationResult doInvokePOST(Object request, Map<String, String> httpHeaders, int retries) throws Exception { if (retries < 0) throw new Exception("Invocation to " + endpointURL + " failed: " + xmlUtil.toString(request)); logger.debug("POST request to: " + endpointURL + " with body " + request); URL url = new URL(endpointURL); URLConnection conn = url.openConnection(); conn.setDoOutput(true);//from ww w . j a va 2s . c o m for (String key : httpHeaders.keySet()) { conn.setRequestProperty(key, httpHeaders.get(key)); } String theRequest = null; if (request instanceof Element) { theRequest = xmlUtil.toString((Element) request); conn.setRequestProperty("Content-Type", "application/xml"); } else if (request instanceof String) { theRequest = (String) request; conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); } BufferedWriter w = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream())); theRequest = theRequest.trim(); w.write(theRequest); w.close(); BufferedReader r = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder b = new StringBuilder(); String temp; while ((temp = r.readLine()) != null) { b.append(temp); b.append("\n"); } String originalResult = b.toString(); String result = originalResult.trim(); if (!result.startsWith("<")) // wrap non-xml results (e.g., CSV files) result = "<doc>" + result + "</doc>"; Element resultElement = xmlUtil.toElement(result); InvocationResult invResult = new InvocationResult(resultElement, originalResult); invResult.getHeaders().putAll(conn.getHeaderFields()); return invResult; }
From source file:org.eclipse.cdt.arduino.core.internal.board.ArduinoManager.java
public synchronized Collection<ArduinoPlatform> getAvailablePlatforms(IProgressMonitor monitor) throws CoreException { List<ArduinoPlatform> platforms = new ArrayList<>(); URL[] urls = ArduinoPreferences.getBoardUrlList(); SubMonitor sub = SubMonitor.convert(monitor, urls.length + 1); sub.beginTask("Downloading package descriptions", urls.length); //$NON-NLS-1$ for (URL url : urls) { Path packagePath = ArduinoPreferences.getArduinoHome().resolve(Paths.get(url.getPath()).getFileName()); try {//from ww w.j av a 2s .c o m Files.createDirectories(ArduinoPreferences.getArduinoHome()); URLConnection connection = url.openConnection(); connection.setRequestProperty("User-Agent", //$NON-NLS-1$ "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2"); //$NON-NLS-1$ try (InputStream in = connection.getInputStream()) { Files.copy(in, packagePath, StandardCopyOption.REPLACE_EXISTING); } } catch (IOException e) { // Log and continue, URLs sometimes come and go Activator.log(e); } sub.worked(1); } sub.beginTask("Loading available packages", 1); //$NON-NLS-1$ resetPackages(); for (ArduinoPackage pkg : getPackages()) { platforms.addAll(pkg.getAvailablePlatforms()); } sub.done(); return platforms; }
From source file:org.tightblog.service.WeblogEntryManager.java
public ValidationResult makeAkismetCall(String apiRequestBody) throws IOException { if (!StringUtils.isBlank(akismetApiKey)) { URL url = new URL("http://" + akismetApiKey + ".rest.akismet.com/1.1/comment-check"); URLConnection conn = url.openConnection(); conn.setDoOutput(true);/*from ww w . j ava 2 s. c om*/ conn.setRequestProperty("User_Agent", "TightBlog"); conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded;charset=utf8"); conn.setRequestProperty("Content-length", Integer.toString(apiRequestBody.length())); OutputStreamWriter osr = new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8); osr.write(apiRequestBody, 0, apiRequestBody.length()); osr.flush(); osr.close(); try (InputStreamReader isr = new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8); BufferedReader br = new BufferedReader(isr)) { String response = br.readLine(); if ("true".equals(response)) { if ("discard".equalsIgnoreCase(conn.getHeaderField("X-akismet-pro-tip"))) { return ValidationResult.BLATANT_SPAM; } return ValidationResult.SPAM; } } } return ValidationResult.NOT_SPAM; }
From source file:com.hp.hpl.jena.grddl.impl.GRDDL.java
private Source xsltStreamSource(String url) throws TransformerException { try {/*from www.ja v a 2s . co m*/ URL urlx = new URL(url); URLConnection conn = urlx.openConnection(); conn.setRequestProperty("accept", "application/xslt+xml; q=1.0, " + "text/xsl; q=0.8, " + "application/xsl; q=0.8, " + "application/xml; q=0.7, " + "text/xml; q=0.6, " + "application/xsl+xml; q=0.8, " + "*/*; q=0.1"); return new StreamSource(conn.getInputStream(), conn.getURL().toString()); } catch (IOException e) { throw new TransformerException(e); } }
From source file:com.recomdata.datasetexplorer.proxy.HttpClient.java
/** * private method to get the URLConnection * @param str URL string//w w w . j a v a 2 s. c o m */ private URLConnection getURLConnection(String str) throws MalformedURLException { try { if (isHttps) { /* when communicating with the server which has unsigned or invalid * certificate (https), SSLException or IOException is thrown. * the following line is a hack to avoid that */ Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol"); if (isProxy) { System.setProperty("https.proxyHost", proxyHost); System.setProperty("https.proxyPort", proxyPort + ""); } } else { if (isProxy) { System.setProperty("http.proxyHost", proxyHost); System.setProperty("http.proxyPort", proxyPort + ""); } } SSLUtilities.trustAllHostnames(); SSLUtilities.trustAllHttpsCertificates(); URL url = new URL(str); URLConnection uc = url.openConnection(); if (isHttps) { /*((HttpsURLConnection)uc).setHostnameVerifier(new HostnameVerifier() { public boolean verify (String hostname, String session) { return true; } });*/ } // set user agent to mimic a common browser String ua = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)"; uc.setRequestProperty("user-agent", ua); return uc; } catch (MalformedURLException me) { throw new MalformedURLException(str + " is not a valid URL"); } catch (Exception e) { e.printStackTrace(); return null; } }
From source file:org.apache.xmlrpc.applet.SimpleXmlRpcClient.java
/** * Generate an XML-RPC request and send it to the server. Parse the result * and return the corresponding Java object. * * @exception XmlRpcException If the remote host returned a fault message. * @exception IOException If the call could not be made for lower level * problems./*from w w w.jav a 2 s . c o m*/ */ public Object execute(String method, Vector arguments) throws XmlRpcException, IOException { fault = false; long now = System.currentTimeMillis(); try { StringBuffer strbuf = new StringBuffer(); XmlWriter writer = new XmlWriter(strbuf); writeRequest(writer, method, arguments); byte[] request = strbuf.toString().getBytes(); URLConnection con = url.openConnection(); con.setDoOutput(true); con.setDoInput(true); con.setUseCaches(false); con.setAllowUserInteraction(false); con.setRequestProperty("Content-Length", Integer.toString(request.length)); con.setRequestProperty("Content-Type", "text/xml"); // con.connect (); OutputStream out = con.getOutputStream(); out.write(request); out.flush(); InputStream in = con.getInputStream(); parse(in); System.out.println("result = " + result); } catch (Exception x) { x.printStackTrace(); throw new IOException(x.getMessage()); } if (fault) { // generate an XmlRpcException XmlRpcException exception = null; try { Hashtable f = (Hashtable) result; String faultString = (String) f.get("faultString"); int faultCode = Integer.parseInt(f.get("faultCode").toString()); exception = new XmlRpcException(faultCode, faultString.trim()); } catch (Exception x) { throw new XmlRpcException(0, "Invalid fault response"); } throw exception; } System.out.println("Spent " + (System.currentTimeMillis() - now) + " in request"); return result; }
From source file:winterwell.jtwitter.URLConnectionHttpClient.java
/** * Set a header for basic authentication login. */// www .j av a2 s . c o m protected void setAuthentication(URLConnection connection, String name, String password) { assert name != null && password != null : "Authentication requested but no login details are set!"; String token = name + ":" + password; String encoding = Base64Encoder.encode(token); connection.setRequestProperty("Authorization", "Basic " + encoding); }