List of usage examples for java.net URLConnection setAllowUserInteraction
public void setAllowUserInteraction(boolean allowuserinteraction)
From source file:com.iskyshop.manage.seller.action.OrderSellerAction.java
private TransInfo query_ship_getData(String id) { TransInfo info = new TransInfo(); OrderForm obj = this.orderFormService.getObjById(CommUtil.null2Long(id)); try {//from ww w. ja v a2 s. c om ExpressCompany ec = this.queryExpressCompany(obj.getExpress_info()); URL url = new URL("http://api.kuaidi100.com/api?id=" + this.configService.getSysConfig().getKuaidi_id() + "&com=" + (ec != null ? ec.getCompany_mark() : "") + "&nu=" + obj.getShipCode() + "&show=0&muti=1&order=asc"); URLConnection con = url.openConnection(); con.setAllowUserInteraction(false); InputStream urlStream = url.openStream(); String type = con.guessContentTypeFromStream(urlStream); String charSet = null; if (type == null) type = con.getContentType(); if (type == null || type.trim().length() == 0 || type.trim().indexOf("text/html") < 0) return info; if (type.indexOf("charset=") > 0) charSet = type.substring(type.indexOf("charset=") + 8); byte b[] = new byte[10000]; int numRead = urlStream.read(b); String content = new String(b, 0, numRead, charSet); while (numRead != -1) { numRead = urlStream.read(b); if (numRead != -1) { // String newContent = new String(b, 0, numRead); String newContent = new String(b, 0, numRead, charSet); content += newContent; } } info = Json.fromJson(TransInfo.class, content); urlStream.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return info; }
From source file:org.signserver.client.cli.validationservice.ValidateCertificateCommand.java
private ValidateResponse runHTTP(final X509Certificate cert) throws Exception { final URL processServlet = new URL(useSSL ? "https" : "http", hosts[0], port, servlet); OutputStream out = null;//from ww w. j a v a 2s . c o m InputStream in = null; try { final URLConnection conn = processServlet.openConnection(); conn.setDoOutput(true); conn.setAllowUserInteraction(false); final StringBuilder sb = new StringBuilder(); sb.append("--" + BOUNDARY); sb.append(CRLF); try { final int workerId = Integer.parseInt(service); sb.append("Content-Disposition: form-data; name=\"workerId\""); sb.append(CRLF); sb.append(CRLF); sb.append(workerId); } catch (NumberFormatException e) { sb.append("Content-Disposition: form-data; name=\"workerName\""); sb.append(CRLF); sb.append(CRLF); sb.append(service); } sb.append(CRLF); sb.append("--" + BOUNDARY); sb.append(CRLF); sb.append("Content-Disposition: form-data; name=\"processType\""); sb.append(CRLF); sb.append(CRLF); sb.append("validateCertificate"); sb.append(CRLF); sb.append("--" + BOUNDARY); sb.append(CRLF); sb.append("Content-Disposition: form-data; name=\"datafile\""); sb.append("; filename=\""); sb.append(certPath.getAbsolutePath()); sb.append("\""); sb.append(CRLF); sb.append("Content-Type: application/octet-stream"); sb.append(CRLF); sb.append("Content-Transfer-Encoding: binary"); sb.append(CRLF); sb.append(CRLF); conn.addRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); out = conn.getOutputStream(); out.write(sb.toString().getBytes()); out.write(cert.getEncoded()); out.write(("\r\n--" + BOUNDARY + "--\r\n").getBytes()); out.flush(); // Get the response in = conn.getInputStream(); final ByteArrayOutputStream os = new ByteArrayOutputStream(); int len; final byte[] buf = new byte[1024]; while ((len = in.read(buf)) > 0) { os.write(buf, 0, len); } os.close(); // read string from response final String response = os.toString(); final String[] responseParts = response.split(";"); // last part of the response string can by empty (revocation date) if (responseParts.length < 4 || responseParts.length > 5) { throw new IOException("Malformed HTTP response"); } final String revocationDateString = responseParts.length == 4 ? null : responseParts[4]; final Date revocationDate = revocationDateString != null && revocationDateString.length() > 0 ? new Date(Integer.valueOf(revocationDateString)) : null; final Validation validation = new Validation(cert, null, Validation.Status.valueOf(responseParts[0]), responseParts[2], revocationDate, Integer.valueOf(responseParts[3])); final ValidateResponse validateResponse = new ValidateResponse(validation, responseParts[1].split(",")); return validateResponse; } catch (IOException e) { throw new RuntimeException(e); } finally { if (out != null) { try { out.close(); } catch (IOException ex) { throw new RuntimeException(ex); } } if (in != null) { try { in.close(); } catch (IOException ex) { throw new RuntimeException(ex); } } } }
From source file:org.openqa.selenium.server.ProxyHandler.java
protected long proxyPlainTextRequest(URL url, String pathInContext, String pathParams, HttpRequest request, HttpResponse response) throws IOException { CaptureNetworkTrafficCommand.Entry entry = new CaptureNetworkTrafficCommand.Entry(request.getMethod(), url.toString());//www.j a v a 2s . c o m entry.addRequestHeaders(request); if (log.isDebugEnabled()) log.debug("PROXY URL=" + url); URLConnection connection = url.openConnection(); connection.setAllowUserInteraction(false); if (proxyInjectionMode) { adjustRequestForProxyInjection(request, connection); } // Set method HttpURLConnection http = null; if (connection instanceof HttpURLConnection) { http = (HttpURLConnection) connection; http.setRequestMethod(request.getMethod()); http.setInstanceFollowRedirects(false); if (trustAllSSLCertificates && connection instanceof HttpsURLConnection) { TrustEverythingSSLTrustManager.trustAllSSLCertificates((HttpsURLConnection) connection); } } // check connection header String connectionHdr = request.getField(HttpFields.__Connection); if (connectionHdr != null && (connectionHdr.equalsIgnoreCase(HttpFields.__KeepAlive) || connectionHdr.equalsIgnoreCase(HttpFields.__Close))) connectionHdr = null; // copy headers boolean xForwardedFor = false; boolean isGet = "GET".equals(request.getMethod()); boolean hasContent = false; Enumeration enm = request.getFieldNames(); while (enm.hasMoreElements()) { // TODO could be better than this! String hdr = (String) enm.nextElement(); if (_DontProxyHeaders.containsKey(hdr) || !_chained && _ProxyAuthHeaders.containsKey(hdr)) continue; if (connectionHdr != null && connectionHdr.indexOf(hdr) >= 0) continue; if (!isGet && HttpFields.__ContentType.equals(hdr)) hasContent = true; Enumeration vals = request.getFieldValues(hdr); while (vals.hasMoreElements()) { String val = (String) vals.nextElement(); if (val != null) { // don't proxy Referer headers if the referer is Selenium! if ("Referer".equals(hdr) && (-1 != val.indexOf("/selenium-server/"))) { continue; } if (!isGet && HttpFields.__ContentLength.equals(hdr) && Integer.parseInt(val) > 0) { hasContent = true; } connection.addRequestProperty(hdr, val); xForwardedFor |= HttpFields.__XForwardedFor.equalsIgnoreCase(hdr); } } } // add any custom request headers that the user asked for Map<String, String> customRequestHeaders = AddCustomRequestHeaderCommand.getHeaders(); for (Map.Entry<String, String> e : customRequestHeaders.entrySet()) { connection.addRequestProperty(e.getKey(), e.getValue()); entry.addRequestHeader(e.getKey(), e.getValue()); } // Proxy headers if (!_anonymous) connection.setRequestProperty("Via", "1.1 (jetty)"); if (!xForwardedFor) connection.addRequestProperty(HttpFields.__XForwardedFor, request.getRemoteAddr()); // a little bit of cache control String cache_control = request.getField(HttpFields.__CacheControl); if (cache_control != null && (cache_control.indexOf("no-cache") >= 0 || cache_control.indexOf("no-store") >= 0)) connection.setUseCaches(false); // customize Connection customizeConnection(pathInContext, pathParams, request, connection); try { connection.setDoInput(true); // do input thang! InputStream in = request.getInputStream(); if (hasContent) { connection.setDoOutput(true); IO.copy(in, connection.getOutputStream()); } // Connect connection.connect(); } catch (Exception e) { LogSupport.ignore(log, e); } InputStream proxy_in = null; // handler status codes etc. int code = -1; if (http != null) { proxy_in = http.getErrorStream(); try { code = http.getResponseCode(); } catch (SSLHandshakeException e) { throw new RuntimeException("Couldn't establish SSL handshake. Try using trustAllSSLCertificates.\n" + e.getLocalizedMessage(), e); } response.setStatus(code); response.setReason(http.getResponseMessage()); String contentType = http.getContentType(); if (log.isDebugEnabled()) { log.debug("Content-Type is: " + contentType); } } if (proxy_in == null) { try { proxy_in = connection.getInputStream(); } catch (Exception e) { LogSupport.ignore(log, e); proxy_in = http.getErrorStream(); } } // clear response defaults. response.removeField(HttpFields.__Date); response.removeField(HttpFields.__Server); // set response headers int h = 0; String hdr = connection.getHeaderFieldKey(h); String val = connection.getHeaderField(h); while (hdr != null || val != null) { if (hdr != null && val != null && !_DontProxyHeaders.containsKey(hdr) && (_chained || !_ProxyAuthHeaders.containsKey(hdr))) response.addField(hdr, val); h++; hdr = connection.getHeaderFieldKey(h); val = connection.getHeaderField(h); } if (!_anonymous) response.setField("Via", "1.1 (jetty)"); response.removeField(HttpFields.__ETag); // possible cksum? Stop caching... response.removeField(HttpFields.__LastModified); // Stop caching... // Handled long bytesCopied = -1; request.setHandled(true); if (proxy_in != null) { boolean injectableResponse = http.getResponseCode() == HttpURLConnection.HTTP_OK || (http.getResponseCode() >= 400 && http.getResponseCode() < 600); if (proxyInjectionMode && injectableResponse) { // check if we should proxy this path based on the dontProxyRegex that can be user-specified if (shouldInject(request.getPath())) { bytesCopied = InjectionHelper.injectJavaScript(request, response, proxy_in, response.getOutputStream(), debugURL); } else { bytesCopied = ModifiedIO.copy(proxy_in, response.getOutputStream()); } } else { bytesCopied = ModifiedIO.copy(proxy_in, response.getOutputStream()); } } entry.finish(code, bytesCopied); entry.addResponseHeader(response); CaptureNetworkTrafficCommand.capture(entry); return bytesCopied; }
From source file:org.lockss.proxy.ProxyHandler.java
/** Proxy a connection using Java's native URLConection */ void doSun(String pathInContext, String pathParams, HttpRequest request, HttpResponse response) throws IOException { URI uri = request.getURI();/*www . ja v a2 s .co m*/ try { // Do we proxy this? URL url = isProxied(uri); if (url == null) { if (isForbidden(uri)) { sendForbid(request, response, uri); logAccess(request, "forbidden method: " + request.getMethod()); } return; } if (jlog.isDebugEnabled()) jlog.debug("PROXY URL=" + url); URLConnection connection = url.openConnection(); connection.setAllowUserInteraction(false); // Set method HttpURLConnection http = null; if (connection instanceof HttpURLConnection) { http = (HttpURLConnection) connection; http.setRequestMethod(request.getMethod()); http.setInstanceFollowRedirects(false); } // check connection header String connectionHdr = request.getField(HttpFields.__Connection); if (connectionHdr != null && (connectionHdr.equalsIgnoreCase(HttpFields.__KeepAlive) || connectionHdr.equalsIgnoreCase(HttpFields.__Close))) connectionHdr = null; // copy headers boolean hasContent = false; Enumeration en = request.getFieldNames(); while (en.hasMoreElements()) { // XXX could be better than this! String hdr = (String) en.nextElement(); if (_DontProxyHeaders.containsKey(hdr)) continue; if (connectionHdr != null && connectionHdr.indexOf(hdr) >= 0) continue; if (HttpFields.__ContentType.equalsIgnoreCase(hdr)) hasContent = true; Enumeration vals = request.getFieldValues(hdr); while (vals.hasMoreElements()) { String val = (String) vals.nextElement(); if (val != null) { connection.addRequestProperty(hdr, val); } } } // Proxy headers connection.addRequestProperty(HttpFields.__Via, makeVia(request)); connection.addRequestProperty(HttpFields.__XForwardedFor, request.getRemoteAddr()); // a little bit of cache control String cache_control = request.getField(HttpFields.__CacheControl); if (cache_control != null && (cache_control.indexOf("no-cache") >= 0 || cache_control.indexOf("no-store") >= 0)) connection.setUseCaches(false); // customize Connection customizeConnection(pathInContext, pathParams, request, connection); try { connection.setDoInput(true); // do input thang! InputStream in = request.getInputStream(); if (hasContent) { connection.setDoOutput(true); IO.copy(in, connection.getOutputStream()); } // Connect connection.connect(); } catch (Exception e) { LogSupport.ignore(jlog, e); } InputStream proxy_in = null; // handler status codes etc. int code = HttpResponse.__500_Internal_Server_Error; if (http != null) { proxy_in = http.getErrorStream(); code = http.getResponseCode(); response.setStatus(code); response.setReason(http.getResponseMessage()); } if (proxy_in == null) { try { proxy_in = connection.getInputStream(); } catch (Exception e) { LogSupport.ignore(jlog, e); proxy_in = http.getErrorStream(); } } // clear response defaults. response.removeField(HttpFields.__Date); response.removeField(HttpFields.__Server); // set response headers int h = 0; String hdr = connection.getHeaderFieldKey(h); String val = connection.getHeaderField(h); while (hdr != null || val != null) { if (hdr != null && val != null && !_DontProxyHeaders.containsKey(hdr)) response.addField(hdr, val); h++; hdr = connection.getHeaderFieldKey(h); val = connection.getHeaderField(h); } response.addField(HttpFields.__Via, makeVia(request)); // Handled request.setHandled(true); if (proxy_in != null) IO.copy(proxy_in, response.getOutputStream()); } catch (Exception e) { log.warning("doSun error", e); if (!response.isCommitted()) response.sendError(HttpResponse.__400_Bad_Request, e.getMessage()); } }
From source file:org.sbs.util.download.MultiThreadDownload.java
/** * /*from w ww. j a va2s . c o m*/ * @param url * @param path * @param fileName * @return * @throws DownLoadException */ @SuppressWarnings("unchecked") public File downLoad(final URL url, String path, String fileName) throws DownLoadException { // ?? this.downLen = -1; this.contentLen = 0; this.date = new Date(); this.finished = false; try { URLConnection con = url.openConnection(); //? this.contentLen = con.getContentLength(); //?? if (StringUtils.isBlank(fileName)) { fileName = StringUtils.substringAfterLast(url.getPath(), "/"); } // File _path = new File(path); if (!_path.exists()) { _path.mkdirs(); } final File file = new File(path + File.separator + fileName); if (file.exists()) file.delete(); if (this.threadNum == 0 && this.blockSize > 0) { this.threadNum = (int) (contentLen / blockSize); if (this.threadNum == 0) { this.threadNum = 1; } } long subLen = contentLen / threadNum; List<Future<DownLoadBean>> result = Lists.newArrayList(); for (int i = 0; i < threadNum; i++) { final int pos = (int) (i * subLen); final int end = (int) ((i + 1) * subLen) - 1; final int current = pos; Future<DownLoadBean> f = (Future<DownLoadBean>) pool.submit(new Callable<DownLoadBean>() { int $pos = pos; int $end = end; int $current = current; @Override public DownLoadBean call() throws Exception { //buff BufferedInputStream bis = null; RandomAccessFile fos = null; byte[] buf = new byte[BUFFER_SIZE]; URLConnection con = null; try { con = url.openConnection(); con.setAllowUserInteraction(true); //???startPosendPos con.setRequestProperty("Range", "bytes=" + $pos + "-" + $end); fos = new RandomAccessFile(file, "rw"); //startPos fos.seek($pos); //????curPos???endPos //endPos? bis = new BufferedInputStream(con.getInputStream()); while ($current < $end) { int len = bis.read(buf, 0, BUFFER_SIZE); if (len == -1) { break; } fos.write(buf, 0, len); $current = $current + len; if ($current - 1 > $end) { throw new DownLoadException( "????"); } addLen(len); } bis.close(); fos.close(); } catch (IOException ex) { /* ????? StringBuffer sb = new StringBuffer(); sb.append($pos).append("\t").append($current).append("\t").append($end).append("\n"); FileUtils.write(new File(file.getAbsolutePath()+".pos"), sb, true); */ throw new RuntimeException(ex); } log.debug(this.hashCode() + ":??[" + $pos + "," + $end + "]"); return new DownLoadBean($pos, $end, $current); } }); result.add(f); } Long resultTotal = 0L; for (Future<DownLoadBean> f : result) { DownLoadBean dInfo = f.get(); resultTotal += dInfo.getCurrent() - dInfo.getPos(); } // ? if (contentLen > resultTotal + 1) { // ??? FileUtils.write(new File(down_error_log_file), url.toString() + "\n", true); throw new DownLoadException("?"); } else { finished = true; return file; } } catch (IOException | InterruptedException | ExecutionException e) { // try { FileUtils.write(new File(down_error_log_file), url.toString() + "\n", true); } catch (IOException e1) { e1.printStackTrace(); } e.printStackTrace(); } return null; }
From source file:com.iskyshop.manage.buyer.action.OrderBuyerAction.java
private TransInfo query_Returnship_getData(String id) { TransInfo info = new TransInfo(); ReturnGoodsLog obj = this.returnGoodsLogService.getObjById(CommUtil.null2Long(id)); try {/*from w w w. ja v a 2s .c o m*/ ExpressCompany ec = this.queryExpressCompany(obj.getReturn_express_info()); String query_url = "http://api.kuaidi100.com/api?id=" + this.configService.getSysConfig().getKuaidi_id() + "&com=" + (ec != null ? ec.getCompany_mark() : "") + "&nu=" + obj.getExpress_code() + "&show=0&muti=1&order=asc"; URL url = new URL(query_url); URLConnection con = url.openConnection(); con.setAllowUserInteraction(false); InputStream urlStream = url.openStream(); String type = con.guessContentTypeFromStream(urlStream); String charSet = null; if (type == null) type = con.getContentType(); if (type == null || type.trim().length() == 0 || type.trim().indexOf("text/html") < 0) return info; if (type.indexOf("charset=") > 0) charSet = type.substring(type.indexOf("charset=") + 8); byte b[] = new byte[10000]; int numRead = urlStream.read(b); String content = new String(b, 0, numRead, charSet); while (numRead != -1) { numRead = urlStream.read(b); if (numRead != -1) { // String newContent = new String(b, 0, numRead); String newContent = new String(b, 0, numRead, charSet); content += newContent; } } info = Json.fromJson(TransInfo.class, content); urlStream.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return info; }
From source file:com.iskyshop.manage.buyer.action.OrderBuyerAction.java
private TransInfo query_ship_getData(String id) { TransInfo info = null;//from w w w . j a v a 2 s . c om OrderForm obj = this.orderFormService.getObjById(CommUtil.null2Long(id)); if (obj != null && !CommUtil.null2String(obj.getShipCode()).equals("")) { info = new TransInfo(); try { ExpressCompany ec = this.queryExpressCompany(obj.getExpress_info()); String query_url = "http://api.kuaidi100.com/api?id=" + this.configService.getSysConfig().getKuaidi_id() + "&com=" + (ec != null ? ec.getCompany_mark() : "") + "&nu=" + obj.getShipCode() + "&show=0&muti=1&order=asc"; URL url = new URL(query_url); URLConnection con = url.openConnection(); con.setAllowUserInteraction(false); InputStream urlStream = url.openStream(); String type = con.guessContentTypeFromStream(urlStream); String charSet = null; if (type == null) type = con.getContentType(); if (type == null || type.trim().length() == 0 || type.trim().indexOf("text/html") < 0) return info; if (type.indexOf("charset=") > 0) charSet = type.substring(type.indexOf("charset=") + 8); byte b[] = new byte[10000]; int numRead = urlStream.read(b); String content = new String(b, 0, numRead, charSet); while (numRead != -1) { numRead = urlStream.read(b); if (numRead != -1) { // String newContent = new String(b, 0, numRead); String newContent = new String(b, 0, numRead, charSet); content += newContent; } } info = Json.fromJson(TransInfo.class, content); urlStream.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return info; }
From source file:com.amalto.workbench.utils.Util.java
public static String getResponseFromURL(String url, TreeObject treeObj) throws Exception { InputStreamReader doc = null; try {//from w ww . j a v a 2s.c o m Encoder encoder = Base64.getEncoder(); StringBuffer buffer = new StringBuffer(); String credentials = encoder.encodeToString((new String(treeObj.getServerRoot().getUsername() + ":"//$NON-NLS-1$ + treeObj.getServerRoot().getPassword()).getBytes())); URL urlCn = new URL(url); URLConnection conn = urlCn.openConnection(); conn.setAllowUserInteraction(true); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Authorization", "Basic " + credentials);//$NON-NLS-1$//$NON-NLS-2$ conn.setRequestProperty("Expect", "100-continue");//$NON-NLS-1$//$NON-NLS-2$ doc = new InputStreamReader(conn.getInputStream()); BufferedReader reader = new BufferedReader(doc); String line = reader.readLine(); while (line != null) { buffer.append(line); line = reader.readLine(); } return buffer.toString(); } finally { if (doc != null) { doc.close(); } } }