List of usage examples for java.net HttpURLConnection setAllowUserInteraction
public void setAllowUserInteraction(boolean allowuserinteraction)
From source file:com.aptana.jira.core.JiraManager.java
@SuppressWarnings("restriction") protected HttpURLConnection createConnection(String urlString, String username, String password) throws MalformedURLException, IOException { HttpURLConnection connection; URL url = new URL(urlString); connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty(USER_AGENT, getProjectVersion()); connection.setRequestProperty(ACCEPT_HEADER, ACCEPT_CONTENT_TYPES); connection.setRequestProperty(CONTENT_TYPE, ACCEPT_CONTENT_TYPES); connection.setUseCaches(false);/* w ww .j av a2 s .c o m*/ connection.setAllowUserInteraction(false); String usernamePassword = username + ":" + password; //$NON-NLS-1$ connection.setRequestProperty(AUTHORIZATION_HEADER, "Basic " + new String(Base64.encode(usernamePassword.getBytes()))); //$NON-NLS-1$ return connection; }
From source file:com.comcast.cdn.traffic_control.traffic_router.core.util.Fetcher.java
protected HttpURLConnection getConnection(final String url, final String data, final String requestMethod, final long lastFetchTime) throws IOException { String method = GET_STR;/*from www. j av a 2 s .c o m*/ if (requestMethod != null) { method = requestMethod; } LOGGER.info(method + "ing: " + url + "; timeout is " + timeout); final URLConnection connection = new URL(url).openConnection(); connection.setIfModifiedSince(lastFetchTime); if (timeout != 0) { connection.setConnectTimeout(timeout); connection.setReadTimeout(timeout); } final HttpURLConnection http = (HttpURLConnection) connection; if (connection instanceof HttpsURLConnection) { final HttpsURLConnection https = (HttpsURLConnection) connection; https.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(final String arg0, final SSLSession arg1) { return true; } }); } http.setInstanceFollowRedirects(false); http.setRequestMethod(method); http.setAllowUserInteraction(true); for (final String key : requestProps.keySet()) { http.addRequestProperty(key, requestProps.get(key)); } if (method.equals(POST_STR) && data != null) { http.setDoOutput(true); // Triggers POST. try (final OutputStream output = http.getOutputStream()) { output.write(data.getBytes(UTF8_STR)); } } connection.connect(); return http; }
From source file:com.docdoku.cli.helpers.FileHelper.java
public String downloadFile(File pLocalFile, String pURL) throws IOException, LoginException, NoSuchAlgorithmException { ConsoleProgressMonitorInputStream in = null; OutputStream out = null;/*from ww w . jav a 2 s. co m*/ HttpURLConnection conn = null; try { //Hack for NTLM proxy //perform a head method to negociate the NTLM proxy authentication URL url = new URL(pURL); System.out.println("Downloading file: " + pLocalFile.getName() + " from " + url.getHost()); performHeadHTTPMethod(url); out = new BufferedOutputStream(new FileOutputStream(pLocalFile), BUFFER_CAPACITY); conn = (HttpURLConnection) url.openConnection(); conn.setUseCaches(false); conn.setAllowUserInteraction(true); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestMethod("GET"); byte[] encoded = Base64.encodeBase64((login + ":" + password).getBytes("ISO-8859-1")); conn.setRequestProperty("Authorization", "Basic " + new String(encoded, "US-ASCII")); conn.connect(); manageHTTPCode(conn); MessageDigest md = MessageDigest.getInstance("MD5"); in = new ConsoleProgressMonitorInputStream(conn.getContentLength(), new DigestInputStream(new BufferedInputStream(conn.getInputStream(), BUFFER_CAPACITY), md)); byte[] data = new byte[CHUNK_SIZE]; int length; while ((length = in.read(data)) != -1) { out.write(data, 0, length); } out.flush(); byte[] digest = md.digest(); return Base64.encodeBase64String(digest); } finally { if (out != null) out.close(); if (in != null) in.close(); if (conn != null) conn.disconnect(); } }
From source file:RhodesService.java
public static boolean pingHost(String host) { HttpURLConnection conn = null; boolean hostExists = false; try {//from www. j a va 2 s .com URL url = new URL(host); HttpURLConnection.setFollowRedirects(false); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("HEAD"); conn.setAllowUserInteraction(false); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setConnectTimeout(10000); conn.setReadTimeout(10000); hostExists = (conn.getContentLength() > 0); if (hostExists) Logger.I(TAG, "PING network SUCCEEDED."); else Logger.E(TAG, "PING network FAILED."); } catch (Exception e) { Logger.E(TAG, e); } finally { if (conn != null) { try { conn.disconnect(); } catch (Exception e) { Logger.E(TAG, e); } } } return hostExists; }
From source file:com.synelixis.xifi.AuthWebClient.Client.java
private String postURL(String url_, String data_, String credentials_) { String urlString = url_;/*w w w .ja v a 2 s. c om*/ String JSON = data_; String credentials = credentials_; try { URL u = new URL(urlString); HttpURLConnection c = (HttpURLConnection) u.openConnection(); c.setDoOutput(true); c.setRequestMethod("POST"); if ((credentials != null) && !credentials.equals("")) { c.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); c.setRequestProperty("Authorization", "Basic " + credentials); } else { c.setRequestProperty("Content-Type", "application/json"); c.setRequestProperty("Accept", "application/json"); } c.setUseCaches(false); c.setAllowUserInteraction(false); OutputStreamWriter out = new OutputStreamWriter(c.getOutputStream()); out.write(JSON); out.flush(); out.close(); System.out.println("url:" + url_ + " -- data:" + data_ + " -- response" + c.getResponseCode()); switch (c.getResponseCode()) { case 200: case 201: BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); String result = sb.toString(); return result; } } catch (MalformedURLException ex) { Logger.getLogger(com.synelixis.xifi.AuthWebClient.Client.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(com.synelixis.xifi.AuthWebClient.Client.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(com.synelixis.xifi.AuthWebClient.Client.class.getName()).log(Level.SEVERE, "Unexpected exception when call the remote server ", ex); } return null; }
From source file:com.google.zxing.web.DecodeServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String imageURIString = request.getParameter("u"); if (imageURIString == null || imageURIString.isEmpty()) { log.info("URI was empty"); response.sendRedirect("badurl.jspx"); return;/*from ww w . j av a 2 s . co m*/ } imageURIString = imageURIString.trim(); for (CharSequence substring : blockedURLSubstrings) { if (imageURIString.contains(substring)) { log.info("Disallowed URI " + imageURIString); response.sendRedirect("badurl.jspx"); return; } } URI imageURI; try { imageURI = new URI(imageURIString); // Assume http: if not specified if (imageURI.getScheme() == null) { imageURI = new URI("http://" + imageURIString); } } catch (URISyntaxException urise) { log.info("URI " + imageURIString + " was not valid: " + urise); response.sendRedirect("badurl.jspx"); return; } // Shortcut for data URI if ("data".equals(imageURI.getScheme())) { try { BufferedImage image = ImageReader.readDataURIImage(imageURI); processImage(image, request, response); } catch (IOException ioe) { log.info(ioe.toString()); response.sendRedirect("badurl.jspx"); } return; } URL imageURL; try { imageURL = imageURI.toURL(); } catch (MalformedURLException ignored) { log.info("URI was not valid: " + imageURIString); response.sendRedirect("badurl.jspx"); return; } String protocol = imageURL.getProtocol(); if (!"http".equalsIgnoreCase(protocol) && !"https".equalsIgnoreCase(protocol)) { log.info("URI was not valid: " + imageURIString); response.sendRedirect("badurl.jspx"); return; } HttpURLConnection connection; try { connection = (HttpURLConnection) imageURL.openConnection(); } catch (IllegalArgumentException ignored) { log.info("URI could not be opened: " + imageURL); response.sendRedirect("badurl.jspx"); return; } connection.setAllowUserInteraction(false); connection.setReadTimeout(5000); connection.setConnectTimeout(5000); connection.setRequestProperty(HttpHeaders.USER_AGENT, "zxing.org"); connection.setRequestProperty(HttpHeaders.CONNECTION, "close"); try { connection.connect(); } catch (IOException ioe) { // Encompasses lots of stuff, including // java.net.SocketException, java.net.UnknownHostException, // javax.net.ssl.SSLPeerUnverifiedException, // org.apache.http.NoHttpResponseException, // org.apache.http.client.ClientProtocolException, log.info(ioe.toString()); response.sendRedirect("badurl.jspx"); return; } try (InputStream is = connection.getInputStream()) { try { if (connection.getResponseCode() != HttpServletResponse.SC_OK) { log.info("Unsuccessful return code: " + connection.getResponseCode()); response.sendRedirect("badurl.jspx"); return; } if (connection.getHeaderFieldInt(HttpHeaders.CONTENT_LENGTH, 0) > MAX_IMAGE_SIZE) { log.info("Too large"); response.sendRedirect("badimage.jspx"); return; } log.info("Decoding " + imageURL); processStream(is, request, response); } finally { consumeRemainder(is); } } catch (IOException ioe) { log.info(ioe.toString()); response.sendRedirect("badurl.jspx"); } finally { connection.disconnect(); } }
From source file:org.ejbca.ui.web.pub.CertRequestHttpTest.java
/** * Tests request for a unknown user/*from w w w .j a v a 2s .c om*/ * * @throws Exception error */ @Test public void test02RequestUnknownUser() throws Exception { log.trace(">test02RequestUnknownUser()"); // POST the OCSP request URL url = new URL(httpReqPath + '/' + resourceReq); HttpURLConnection con = (HttpURLConnection) url.openConnection(); // we are going to do a POST con.setDoOutput(true); con.setRequestMethod("POST"); con.setInstanceFollowRedirects(false); con.setAllowUserInteraction(false); // POST it con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); OutputStream os = con.getOutputStream(); os.write("user=reqtestunknown&password=foo123&keylength=2048".getBytes("UTF-8")); os.close(); final int responseCode = con.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { log.info("ResponseMessage: " + con.getResponseMessage()); assertEquals("Response code", HttpURLConnection.HTTP_OK, responseCode); } log.info("Content-Type: " + con.getContentType()); boolean ok = false; // Some containers return the content type with a space and some // without... if ("text/html;charset=UTF-8".equals(con.getContentType())) { ok = true; } if ("text/html; charset=UTF-8".equals(con.getContentType())) { ok = true; } assertTrue(con.getContentType(), ok); ByteArrayOutputStream baos = new ByteArrayOutputStream(); // This works for small requests, and PKCS12 requests are small InputStream in = con.getInputStream(); int b = in.read(); while (b != -1) { baos.write(b); b = in.read(); } baos.flush(); in.close(); byte[] respBytes = baos.toByteArray(); String error = new String(respBytes); int index = error.indexOf("<pre>"); int index2 = error.indexOf("</pre>"); String errormsg = error.substring(index + 5, index2); log.info(errormsg); String expectedErrormsg = "Username: reqtestunknown\nNon existent username. To generate a certificate a valid username and password must be supplied.\n"; assertEquals(expectedErrormsg.replaceAll("\\s", ""), errormsg.replaceAll("\\s", "")); log.trace("<test02RequestUnknownUser()"); }
From source file:org.ejbca.ui.web.pub.CertRequestHttpTest.java
/** * Tests request for a wrong password/*w ww.jav a 2 s . c o m*/ * * @throws Exception error */ @Test public void test03RequestWrongPwd() throws Exception { log.trace(">test03RequestWrongPwd()"); setupUser(SecConst.TOKEN_SOFT_P12); // POST the OCSP request URL url = new URL(httpReqPath + '/' + resourceReq); HttpURLConnection con = (HttpURLConnection) url.openConnection(); // we are going to do a POST con.setDoOutput(true); con.setRequestMethod("POST"); con.setInstanceFollowRedirects(false); con.setAllowUserInteraction(false); // POST it con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); OutputStream os = con.getOutputStream(); os.write(("user=" + TEST_USERNAME + "&password=foo456&keylength=2048").getBytes("UTF-8")); os.close(); final int responseCode = con.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { log.info("ResponseMessage: " + con.getResponseMessage()); assertEquals("Response code", HttpURLConnection.HTTP_OK, responseCode); } boolean ok = false; // Some containers return the content type with a space and some // without... if ("text/html;charset=UTF-8".equals(con.getContentType())) { ok = true; } if ("text/html; charset=UTF-8".equals(con.getContentType())) { ok = true; } assertTrue(con.getContentType(), ok); ByteArrayOutputStream baos = new ByteArrayOutputStream(); // This works for small requests, and PKCS12 requests are small InputStream in = con.getInputStream(); int b = in.read(); while (b != -1) { baos.write(b); b = in.read(); } baos.flush(); in.close(); byte[] respBytes = baos.toByteArray(); String error = new String(respBytes); int index = error.indexOf("<pre>"); int index2 = error.indexOf("</pre>"); String errormsg = error.substring(index + 5, index2); String expectedErrormsg = "Username: " + TEST_USERNAME + "\nWrong username or password"; assertEquals(expectedErrormsg.replaceAll("\\s", ""), errormsg.replaceAll("\\s", "")); log.info(errormsg); log.trace("<test03RequestWrongPwd()"); }
From source file:cz.incad.kramerius.k5indexer.Commiter.java
/** * Reads data from the data reader and posts it to solr, writes the response * to output// w w w.j av a 2 s .c o m */ private void postData(URL url, Reader data, String contentType, StringBuilder output) throws Exception { HttpURLConnection urlc = null; try { urlc = (HttpURLConnection) url.openConnection(); urlc.setConnectTimeout(config.getInt("http.timeout", 10000)); try { urlc.setRequestMethod("POST"); } catch (ProtocolException e) { throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e); } urlc.setDoOutput(true); urlc.setDoInput(true); urlc.setUseCaches(false); urlc.setAllowUserInteraction(false); urlc.setRequestProperty("Content-type", contentType); OutputStream out = urlc.getOutputStream(); try { Writer writer = new OutputStreamWriter(out, "UTF-8"); pipe(data, writer); writer.close(); } catch (IOException e) { throw new Exception("IOException while posting data", e); } finally { if (out != null) { out.close(); } } InputStream in = urlc.getInputStream(); int status = urlc.getResponseCode(); StringBuilder errorStream = new StringBuilder(); try { if (status != HttpURLConnection.HTTP_OK) { errorStream.append("postData URL=").append(solrUrl).append(" HTTP response code=") .append(status).append(" "); throw new Exception("URL=" + solrUrl + " HTTP response code=" + status); } Reader reader = new InputStreamReader(in); pipeString(reader, output); reader.close(); } catch (IOException e) { throw new Exception("IOException while reading response", e); } finally { if (in != null) { in.close(); } } InputStream es = urlc.getErrorStream(); if (es != null) { try { Reader reader = new InputStreamReader(es); pipeString(reader, errorStream); reader.close(); } catch (IOException e) { throw new Exception("IOException while reading response", e); } finally { if (es != null) { es.close(); } } } if (errorStream.length() > 0) { throw new Exception("postData error: " + errorStream.toString()); } } catch (IOException e) { throw new Exception("Solr has throw an error. Check tomcat log. " + e); } finally { if (urlc != null) { urlc.disconnect(); } } }
From source file:org.ejbca.ui.web.pub.CertRequestHttpTest.java
/** * Tests request with wrong status//from w w w . ja va 2 s .c o m * * @throws Exception error */ @Test public void test04RequestWrongStatus() throws Exception { log.trace(">test04RequestWrongStatus()"); setupUser(SecConst.TOKEN_SOFT_P12); setupUserStatus(EndEntityConstants.STATUS_GENERATED); // POST the OCSP request URL url = new URL(httpReqPath + '/' + resourceReq); HttpURLConnection con = (HttpURLConnection) url.openConnection(); // we are going to do a POST con.setDoOutput(true); con.setRequestMethod("POST"); con.setInstanceFollowRedirects(false); con.setAllowUserInteraction(false); // POST it con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); OutputStream os = con.getOutputStream(); os.write(("user=" + TEST_USERNAME + "&password=foo456&keylength=2048").getBytes("UTF-8")); os.close(); final int responseCode = con.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { log.info("ResponseMessage: " + con.getResponseMessage()); assertEquals("Response code", HttpURLConnection.HTTP_OK, responseCode); } boolean ok = false; // Some containers return the content type with a space and some // without... if ("text/html;charset=UTF-8".equals(con.getContentType())) { ok = true; } if ("text/html; charset=UTF-8".equals(con.getContentType())) { ok = true; } assertTrue(con.getContentType(), ok); ByteArrayOutputStream baos = new ByteArrayOutputStream(); // This works for small requests, and PKCS12 requests are small InputStream in = con.getInputStream(); int b = in.read(); while (b != -1) { baos.write(b); b = in.read(); } baos.flush(); in.close(); byte[] respBytes = baos.toByteArray(); String error = new String(respBytes); int index = error.indexOf("<pre>"); int index2 = error.indexOf("</pre>"); String errormsg = error.substring(index + 5, index2); String expectedErrormsg = "Username: " + TEST_USERNAME + "\nWrong user status! To generate a certificate for a user the user must have status New, Failed or In process.\n"; assertEquals(expectedErrormsg.replaceAll("\\s", ""), errormsg.replaceAll("\\s", "")); log.info(errormsg); log.trace("<test04RequestWrongStatus()"); }