List of usage examples for java.net HttpURLConnection getHeaderField
public String getHeaderField(int n)
From source file:org.openbravo.erpCommon.modules.ImportModule.java
/** * Obtains remotely an obx for the desired moduleVersionID * //from www. j a va 2s. c om */ private RemoteModule getRemoteModule(String moduleVersionID) { RemoteModule remoteModule = new RemoteModule(); WebService3ImplServiceLocator loc; WebService3Impl ws = null; String strUrl = ""; boolean isCommercial; try { loc = new WebService3ImplServiceLocator(); ws = loc.getWebService3(); } catch (final Exception e) { log4j.error(e); addLog("@CouldntConnectToWS@", ImportModule.MSG_ERROR); try { ImportModuleData.insertLog(ImportModule.pool, (vars == null ? "0" : vars.getUser()), "", "", "", "Couldn't contact with webservice server", "E"); } catch (final ServletException ex) { log4j.error(ex); } remoteModule.setError(true); return remoteModule; } try { isCommercial = ws.isCommercial(moduleVersionID); strUrl = ws.getURLforDownload(moduleVersionID); } catch (AxisFault e1) { addLog("@" + e1.getFaultCode() + "@", ImportModule.MSG_ERROR); remoteModule.setError(true); return remoteModule; } catch (RemoteException e) { addLog(e.getMessage(), ImportModule.MSG_ERROR); remoteModule.setError(true); return remoteModule; } if (isCommercial && !ActivationKey.isActiveInstance()) { addLog("@NotCommercialModulesAllowed@", ImportModule.MSG_ERROR); remoteModule.setError(true); return remoteModule; } try { URL url = new URL(strUrl); HttpURLConnection conn = null; if (strUrl.startsWith("https://")) { ActivationKey ak = ActivationKey.getInstance(); String instanceKey = "obinstance=" + URLEncoder.encode(ak.getPublicKey(), "utf-8"); conn = HttpsUtils.sendHttpsRequest(url, instanceKey); } else { conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Keep-Alive", "300"); conn.setRequestProperty("Connection", "keep-alive"); conn.setRequestMethod("GET"); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setAllowUserInteraction(false); } if (conn.getResponseCode() == HttpServletResponse.SC_OK) { // OBX is ready to be used remoteModule.setObx(conn.getInputStream()); String size = conn.getHeaderField("Content-Length"); if (size != null) { remoteModule.setSize(new Integer(size)); } return remoteModule; } // There is an error, let's check for a parseable message String msg = conn.getHeaderField("OB-ErrMessage"); if (msg != null) { addLog(msg, ImportModule.MSG_ERROR); } else { addLog("@ErrorDownloadingOBX@ " + conn.getResponseCode(), ImportModule.MSG_ERROR); } } catch (Exception e) { addLog("@ErrorDownloadingOBX@ " + e.getMessage(), ImportModule.MSG_ERROR); } remoteModule.setError(true); return remoteModule; }
From source file:io.wittmann.jiralist.servlet.ProxyServlet.java
/** * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) *///from w w w .j ava2 s. c o m @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { long requestId = requestCounter++; String proxyTo = "https://issues.jboss.org/rest/api/2"; if (req.getHeader("X-Proxy-To") != null) { proxyTo = req.getHeader("X-Proxy-To"); } String url = proxyTo + req.getPathInfo(); if (req.getQueryString() != null) { url += "?" + req.getQueryString(); } System.out.println("[" + requestId + "]: Proxying to: " + url); boolean isWrite = req.getMethod().equalsIgnoreCase("post") || req.getMethod().equalsIgnoreCase("put"); URL remoteUrl = new URL(url); HttpURLConnection remoteConn = (HttpURLConnection) remoteUrl.openConnection(); if (isWrite) { remoteConn.setDoOutput(true); } remoteConn.setRequestMethod(req.getMethod()); String auth = req.getHeader("Authorization"); if (auth != null) { remoteConn.setRequestProperty("Authorization", auth); } String ct = req.getHeader("Content-Type"); if (ct != null) { remoteConn.setRequestProperty("Content-Type", ct); } String cl = req.getHeader("Content-Length"); if (cl != null) { remoteConn.setRequestProperty("Content-Length", cl); } String accept = req.getHeader("Accept"); if (accept != null) { remoteConn.setRequestProperty("Accept", accept); } System.out.println("[" + requestId + "]: Request Info:"); System.out.println("[" + requestId + "]: Method: " + req.getMethod()); System.out.println("[" + requestId + "]: Has auth: " + (auth != null)); System.out.println("[" + requestId + "]: Content-Type: " + ct); System.out.println("[" + requestId + "]: Content-Length: " + cl); if (isWrite) { InputStream requestIS = null; OutputStream remoteOS = null; try { requestIS = req.getInputStream(); remoteOS = remoteConn.getOutputStream(); IOUtils.copy(requestIS, remoteOS); remoteOS.flush(); } catch (Exception e) { e.printStackTrace(); resp.sendError(500, e.getMessage()); return; } finally { IOUtils.closeQuietly(requestIS); IOUtils.closeQuietly(remoteOS); } } InputStream remoteIS = null; OutputStream responseOS = null; int responseCode = remoteConn.getResponseCode(); System.out.println("[" + requestId + "]: Response Info:"); System.out.println("[" + requestId + "]: Code: " + responseCode); if (responseCode == 400) { remoteIS = remoteConn.getInputStream(); responseOS = System.out; IOUtils.copy(remoteIS, responseOS); IOUtils.closeQuietly(remoteIS); resp.sendError(400, "Error 400"); } else { try { Map<String, List<String>> headerFields = remoteConn.getHeaderFields(); for (String headerName : headerFields.keySet()) { if (headerName == null) { continue; } if (EXCLUDE_HEADERS.contains(headerName)) { continue; } String headerValue = remoteConn.getHeaderField(headerName); resp.setHeader(headerName, headerValue); System.out.println("[" + requestId + "]: " + headerName + " : " + headerValue); } resp.setHeader("Cache-control", "no-cache, no-store, must-revalidate"); //$NON-NLS-2$ remoteIS = remoteConn.getInputStream(); responseOS = resp.getOutputStream(); int bytesCopied = IOUtils.copy(remoteIS, responseOS); System.out.println("[" + requestId + "]: Bytes Proxied: " + bytesCopied); resp.flushBuffer(); } catch (Exception e) { e.printStackTrace(); resp.sendError(500, e.getMessage()); } finally { IOUtils.closeQuietly(responseOS); IOUtils.closeQuietly(remoteIS); } } }
From source file:org.springframework.security.oauth.consumer.client.CoreOAuthConsumerSupport.java
/** * Read a resource.// www .j a va2s .c om * * @param details The details of the resource. * @param url The URL of the resource. * @param httpMethod The http method. * @param token The token. * @param additionalParameters Any additional request parameters. * @param additionalRequestHeaders Any additional request parameters. * @return The resource. */ protected InputStream readResource(ProtectedResourceDetails details, URL url, String httpMethod, OAuthConsumerToken token, Map<String, String> additionalParameters, Map<String, String> additionalRequestHeaders) { url = configureURLForProtectedAccess(url, token, details, httpMethod, additionalParameters); String realm = details.getAuthorizationHeaderRealm(); boolean sendOAuthParamsInRequestBody = !details.isAcceptsAuthorizationHeader() && (("POST".equalsIgnoreCase(httpMethod) || "PUT".equalsIgnoreCase(httpMethod))); HttpURLConnection connection = openConnection(url); try { connection.setRequestMethod(httpMethod); } catch (ProtocolException e) { throw new IllegalStateException(e); } Map<String, String> reqHeaders = details.getAdditionalRequestHeaders(); if (reqHeaders != null) { for (Map.Entry<String, String> requestHeader : reqHeaders.entrySet()) { connection.setRequestProperty(requestHeader.getKey(), requestHeader.getValue()); } } if (additionalRequestHeaders != null) { for (Map.Entry<String, String> requestHeader : additionalRequestHeaders.entrySet()) { connection.setRequestProperty(requestHeader.getKey(), requestHeader.getValue()); } } int responseCode; String responseMessage; try { connection.setDoOutput(sendOAuthParamsInRequestBody); connection.connect(); if (sendOAuthParamsInRequestBody) { String queryString = getOAuthQueryString(details, token, url, httpMethod, additionalParameters); OutputStream out = connection.getOutputStream(); out.write(queryString.getBytes("UTF-8")); out.flush(); out.close(); } responseCode = connection.getResponseCode(); responseMessage = connection.getResponseMessage(); if (responseMessage == null) { responseMessage = "Unknown Error"; } } catch (IOException e) { throw new OAuthRequestFailedException("OAuth connection failed.", e); } if (responseCode >= 200 && responseCode < 300) { try { return connection.getInputStream(); } catch (IOException e) { throw new OAuthRequestFailedException("Unable to get the input stream from a successful response.", e); } } else if (responseCode == 400) { throw new OAuthRequestFailedException("OAuth authentication failed: " + responseMessage); } else if (responseCode == 401) { String authHeaderValue = connection.getHeaderField("WWW-Authenticate"); if (authHeaderValue != null) { Map<String, String> headerEntries = StringSplitUtils.splitEachArrayElementAndCreateMap( StringSplitUtils.splitIgnoringQuotes(authHeaderValue, ','), "=", "\""); String requiredRealm = headerEntries.get("realm"); if ((requiredRealm != null) && (!requiredRealm.equals(realm))) { throw new InvalidOAuthRealmException(String.format( "Invalid OAuth realm. Provider expects \"%s\", when the resource details specify \"%s\".", requiredRealm, realm), requiredRealm); } } throw new OAuthRequestFailedException("OAuth authentication failed: " + responseMessage); } else { throw new OAuthRequestFailedException( String.format("Invalid response code %s (%s).", responseCode, responseMessage)); } }
From source file:ca.osmcanada.osvuploadr.JPMain.java
private String sendForm(String target_url, Map<String, String> arguments, String method, List<Cookie> cookielist) { try {/*from w w w .ja va 2 s .c o m*/ URL url = new URL(target_url); HttpURLConnection con = (HttpURLConnection) url.openConnection(); //HttpURLConnection http = (HttpURLConnection)con; con.setRequestMethod(method); // PUT is another valid option con.setDoOutput(true); con.setInstanceFollowRedirects(false); String cookiestr = ""; if (cookielist != null) { if (cookielist.size() > 0) { for (Cookie cookie : cookielist) { if (!cookiestr.equals("")) { cookiestr += ";" + cookie.getName() + "=" + cookie.getValue(); } else { cookiestr += cookie.getName() + "=" + cookie.getValue(); } } con.setRequestProperty("Cookie", cookiestr); } } con.setReadTimeout(5000); StringJoiner sj = new StringJoiner("&"); for (Map.Entry<String, String> entry : arguments.entrySet()) sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "=" + URLEncoder.encode(entry.getValue(), "UTF-8")); byte[] out = sj.toString().getBytes(StandardCharsets.UTF_8); int length = out.length; con.setFixedLengthStreamingMode(length); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); con.setRequestProperty("Accept-Language", "en-us;"); con.connect(); try (OutputStream os = con.getOutputStream()) { os.write(out); os.close(); } boolean redirect = false; int status = con.getResponseCode(); if (status != HttpURLConnection.HTTP_OK) { if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER) redirect = true; } if (redirect) { String newURL = con.getHeaderField("Location"); String cookies = con.getHeaderField("Set-Cookie"); if (cookies == null) { cookies = cookiestr; } con = (HttpURLConnection) new URL(newURL).openConnection(); con.setRequestProperty("Cookie", cookies); } InputStream is = con.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte buf[] = new byte[1024]; int letti; while ((letti = is.read(buf)) > 0) baos.write(buf, 0, letti); String data = new String(baos.toByteArray(), Charset.forName("UTF-8")); con.disconnect(); return data; } catch (Exception ex) { Logger.getLogger(JPMain.class.getName()).log(Level.SEVERE, null, ex); } return ""; }
From source file:org.runnerup.export.FunBeatUploader.java
@Override public Status connect() { Exception ex = null;//from ww w .j a v a 2 s .c om HttpURLConnection conn = null; cookies.clear(); formValues.clear(); Status s = Status.NEED_AUTH; s.authMethod = AuthMethod.USER_PASS; if (username == null || password == null) { return s; } if (loginID == null || loginSecretHashed == null) { if (!validateAndCreateSecrets(username, password)) return s; } try { /** * connect to START_URL to get cookies/formValues */ conn = (HttpURLConnection) new URL(START_URL).openConnection(); conn.setInstanceFollowRedirects(false); { int responseCode = conn.getResponseCode(); String amsg = conn.getResponseMessage(); getCookies(conn); getFormValues(conn); System.out.println("FunBeat.START_URL => code: " + responseCode + "(" + amsg + "), cookies: " + cookies.size() + ", values: " + formValues.size()); } conn.disconnect(); /** * Then login using a post */ FormValues kv = new FormValues(); String viewKey = findName(formValues.keySet(), "VIEWSTATE"); String eventKey = findName(formValues.keySet(), "EVENTVALIDATION"); String userKey = findName(formValues.keySet(), "Username"); String passKey = findName(formValues.keySet(), "Password"); String loginKey = findName(formValues.keySet(), "LoginButton"); kv.put(viewKey, formValues.get(viewKey)); kv.put(eventKey, formValues.get(eventKey)); kv.put(userKey, username); kv.put(passKey, password); kv.put(loginKey, "Logga in"); conn = (HttpURLConnection) new URL(LOGIN_URL).openConnection(); conn.setInstanceFollowRedirects(false); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); addCookies(conn); boolean ok = false; { OutputStream wr = new BufferedOutputStream(conn.getOutputStream()); kv.write(wr); wr.flush(); wr.close(); int responseCode = conn.getResponseCode(); String amsg = conn.getResponseMessage(); getCookies(conn); if (responseCode == 302) { String redirect = conn.getHeaderField("Location"); conn.disconnect(); conn = (HttpURLConnection) new URL(BASE_URL + redirect).openConnection(); conn.setInstanceFollowRedirects(false); conn.setRequestMethod("GET"); addCookies(conn); responseCode = conn.getResponseCode(); amsg = conn.getResponseMessage(); getCookies(conn); } else if (responseCode != 200) { System.err.println("FunBeatUploader::connect() - got " + responseCode + ", msg: " + amsg); } String html = getFormValues(conn); ok = html.indexOf("Logga ut") > 0; conn.disconnect(); } if (ok) { return Uploader.Status.OK; } else { return s; } } catch (MalformedURLException e) { ex = e; } catch (IOException e) { ex = e; } if (conn != null) conn.disconnect(); s.ex = ex; if (ex != null) { ex.printStackTrace(); } return s; }
From source file:org.vfny.geoserver.wfs.servlets.TestWfsPost.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// w ww . j a va 2s . co m * * @param request servlet request * @param response servlet response * * @throws ServletException DOCUMENT ME! * @throws IOException DOCUMENT ME! */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String requestString = request.getParameter("body"); String urlString = request.getParameter("url"); boolean doGet = (requestString == null) || requestString.trim().equals(""); if ((urlString == null)) { PrintWriter out = response.getWriter(); StringBuffer urlInfo = request.getRequestURL(); if (urlInfo.indexOf("?") != -1) { urlInfo.delete(urlInfo.indexOf("?"), urlInfo.length()); } String geoserverUrl = urlInfo.substring(0, urlInfo.indexOf("/", 8)) + request.getContextPath(); response.setContentType("text/html"); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">"); out.println("<html>"); out.println("<head>"); out.println("<title>TestWfsPost</title>"); out.println("</head>"); out.println("<script language=\"JavaScript\">"); out.println("function doNothing() {"); out.println("}"); out.println("function sendRequest() {"); out.println(" if (checkURL()==true) {"); out.print(" document.frm.action = \""); out.print(urlInfo.toString()); out.print("\";\n"); out.println(" document.frm.target = \"_blank\";"); out.println(" document.frm.submit();"); out.println(" }"); out.println("}"); out.println("function checkURL() {"); out.println(" if (document.frm.url.value==\"\") {"); out.println(" alert(\"Please give URL before you sumbit this form!\");"); out.println(" return false;"); out.println(" } else {"); out.println(" return true;"); out.println(" }"); out.println("}"); out.println("function clearRequest() {"); out.println("document.frm.body.value = \"\";"); out.println("}"); out.println("</script>"); out.println("<body>"); out.println("<form name=\"frm\" action=\"JavaScript:doNothing()\" method=\"POST\">"); out.println("<table align=\"center\" cellspacing=\"2\" cellpadding=\"2\" border=\"0\">"); out.println("<tr>"); out.println("<td><b>URL:</b></td>"); out.print("<td><input name=\"url\" value=\""); out.print(geoserverUrl); out.print("/wfs/GetFeature\" size=\"70\" MAXLENGTH=\"100\"/></td>\n"); out.println("</tr>"); out.println("<tr>"); out.println("<td><b>Request:</b></td>"); out.println("<td><textarea cols=\"60\" rows=\"24\" name=\"body\"></textarea></td>"); out.println("</tr>"); out.println("</table>"); out.println("<table align=\"center\">"); out.println("<tr>"); out.println("<td><input type=\"button\" value=\"Clear\" onclick=\"clearRequest()\"></td>"); out.println("<td><input type=\"button\" value=\"Submit\" onclick=\"sendRequest()\"></td>"); out.println("<td></td>"); out.println("</tr>"); out.println("</table>"); out.println("</form>"); out.println("</body>"); out.println("</html>"); out.close(); } else { response.setContentType("application/xml"); BufferedReader xmlIn = null; PrintWriter xmlOut = null; StringBuffer sbf = new StringBuffer(); String resp = null; try { URL u = new URL(urlString); java.net.HttpURLConnection acon = (java.net.HttpURLConnection) u.openConnection(); acon.setAllowUserInteraction(false); if (!doGet) { //System.out.println("set to post"); acon.setRequestMethod("POST"); acon.setRequestProperty("Content-Type", "application/xml"); } else { //System.out.println("set to get"); acon.setRequestMethod("GET"); } acon.setDoOutput(true); acon.setDoInput(true); acon.setUseCaches(false); //SISfixed - if there was authentication info in the request, // Pass it along the way to the target URL //DJB: applied patch in GEOS-335 String authHeader = request.getHeader("Authorization"); String username = request.getParameter("username"); if ((username != null) && !username.trim().equals("")) { String password = request.getParameter("password"); String up = username + ":" + password; byte[] encoded = Base64.encodeBase64(up.getBytes()); authHeader = "Basic " + new String(encoded); } if (authHeader != null) { acon.setRequestProperty("Authorization", authHeader); } if (!doGet) { xmlOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(acon.getOutputStream()))); xmlOut = new java.io.PrintWriter(acon.getOutputStream()); xmlOut.write(requestString); xmlOut.flush(); } // Above 400 they're all error codes, see: // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html if (acon.getResponseCode() >= 400) { PrintWriter out = response.getWriter(); out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); out.println("<servlet-exception>"); out.println("HTTP response: " + acon.getResponseCode() + "\n" + URLDecoder.decode(acon.getResponseMessage(), "UTF-8")); out.println("</servlet-exception>"); out.close(); } else { // xmlIn = new BufferedReader(new InputStreamReader( // acon.getInputStream())); // String line; // System.out.println("got encoding from acon: " // + acon.getContentType()); response.setContentType(acon.getContentType()); response.setHeader("Content-disposition", acon.getHeaderField("Content-disposition")); OutputStream output = response.getOutputStream(); int c; InputStream in = acon.getInputStream(); while ((c = in.read()) != -1) output.write(c); in.close(); output.close(); } //while ((line = xmlIn.readLine()) != null) { // out.print(line); //} } catch (Exception e) { PrintWriter out = response.getWriter(); out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); out.println("<servlet-exception>"); out.println(e.toString()); out.println("</servlet-exception>"); out.close(); } finally { try { if (xmlIn != null) { xmlIn.close(); } } catch (Exception e1) { PrintWriter out = response.getWriter(); out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); out.println("<servlet-exception>"); out.println(e1.toString()); out.println("</servlet-exception>"); out.close(); } try { if (xmlOut != null) { xmlOut.close(); } } catch (Exception e2) { PrintWriter out = response.getWriter(); out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); out.println("<servlet-exception>"); out.println(e2.toString()); out.println("</servlet-exception>"); out.close(); } } } }
From source file:com.techventus.server.voice.Voice.java
/** * HTTP GET request for a given URL String. * /*from w w w. j a va2s . c o m*/ * @param urlString * the url string * @return the string * @throws IOException * Signals that an I/O exception has occurred. */ String get(String urlString) throws IOException { URL url = new URL(urlString); //+ "?auth=" + URLEncoder.encode(authToken, enc)); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Authorization", "GoogleLogin auth=" + authToken); conn.setRequestProperty("User-agent", USER_AGENT); conn.setInstanceFollowRedirects(false); // will follow redirects of same protocol http to http, but does not follow from http to https for example if set to true // Get the response conn.connect(); int responseCode = conn.getResponseCode(); if (PRINT_TO_CONSOLE) System.out.println(urlString + " - " + conn.getResponseMessage()); InputStream is; if (responseCode == 200) { is = conn.getInputStream(); } else if (responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_MOVED_TEMP || responseCode == HttpURLConnection.HTTP_SEE_OTHER || responseCode == 307) { redirectCounter++; if (redirectCounter > MAX_REDIRECTS) { redirectCounter = 0; throw new IOException(urlString + " : " + conn.getResponseMessage() + "(" + responseCode + ") : Too manny redirects. exiting."); } String location = conn.getHeaderField("Location"); if (location != null && !location.equals("")) { System.out.println(urlString + " - " + responseCode + " - new URL: " + location); return get(location); } else { throw new IOException(urlString + " : " + conn.getResponseMessage() + "(" + responseCode + ") : Received moved answer but no Location. exiting."); } } else { is = conn.getErrorStream(); } redirectCounter = 0; if (is == null) { throw new IOException(urlString + " : " + conn.getResponseMessage() + "(" + responseCode + ") : InputStream was null : exiting."); } String result = ""; try { // Get the response BufferedReader rd = new BufferedReader(new InputStreamReader(is)); StringBuffer sb = new StringBuffer(); String line; while ((line = rd.readLine()) != null) { sb.append(line + "\n\r"); } rd.close(); result = sb.toString(); } catch (Exception e) { throw new IOException(urlString + " - " + conn.getResponseMessage() + "(" + responseCode + ") - " + e.getLocalizedMessage()); } return result; }
From source file:org.runnerup.export.FunBeatSynchronizer.java
@Override public Status connect() { Exception ex = null;// ww w . j a v a2 s . c o m HttpURLConnection conn = null; cookies.clear(); formValues.clear(); Status s = Status.NEED_AUTH; s.authMethod = AuthMethod.USER_PASS; if (username == null || password == null) { return s; } if (loginID == null || loginSecretHashed == null) { if (!validateAndCreateSecrets(username, password)) return s; } try { /** * connect to START_URL to get cookies/formValues */ conn = (HttpURLConnection) new URL(START_URL).openConnection(); conn.setInstanceFollowRedirects(false); { int responseCode = conn.getResponseCode(); String amsg = conn.getResponseMessage(); getCookies(conn); getFormValues(conn); Log.i(getName(), "FunBeat.START_URL => code: " + responseCode + "(" + amsg + "), cookies: " + cookies.size() + ", values: " + formValues.size()); } conn.disconnect(); /** * Then login using a post */ FormValues kv = new FormValues(); String viewKey = SyncHelper.findName(formValues.keySet(), "VIEWSTATE"); String eventKey = SyncHelper.findName(formValues.keySet(), "EVENTVALIDATION"); String userKey = SyncHelper.findName(formValues.keySet(), "Username"); String passKey = SyncHelper.findName(formValues.keySet(), "Password"); String loginKey = SyncHelper.findName(formValues.keySet(), "LoginButton"); kv.put(viewKey, formValues.get(viewKey)); kv.put(eventKey, formValues.get(eventKey)); kv.put(userKey, username); kv.put(passKey, password); kv.put(loginKey, "Logga in"); conn = (HttpURLConnection) new URL(LOGIN_URL).openConnection(); conn.setInstanceFollowRedirects(false); conn.setDoOutput(true); conn.setRequestMethod(RequestMethod.POST.name()); conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); addCookies(conn); boolean ok = false; { OutputStream wr = new BufferedOutputStream(conn.getOutputStream()); kv.write(wr); wr.flush(); wr.close(); int responseCode = conn.getResponseCode(); String amsg = conn.getResponseMessage(); getCookies(conn); if (responseCode == HttpStatus.SC_MOVED_TEMPORARILY) { String redirect = conn.getHeaderField("Location"); conn.disconnect(); conn = (HttpURLConnection) new URL(BASE_URL + redirect).openConnection(); conn.setInstanceFollowRedirects(false); conn.setRequestMethod(RequestMethod.GET.name()); addCookies(conn); responseCode = conn.getResponseCode(); amsg = conn.getResponseMessage(); getCookies(conn); } else if (responseCode != HttpStatus.SC_OK) { Log.e(getName(), "FunBeatSynchronizer::connect() - got " + responseCode + ", msg: " + amsg); } String html = getFormValues(conn); ok = html.indexOf("Logga ut") > 0; conn.disconnect(); } if (ok) { return Synchronizer.Status.OK; } else { return s; } } catch (MalformedURLException e) { ex = e; } catch (IOException e) { ex = e; } if (conn != null) conn.disconnect(); s.ex = ex; if (ex != null) { ex.printStackTrace(); } return s; }
From source file:org.webcurator.core.archive.oms.OMSUploadUtil.java
/** * Add an OMS object based upon files uploaded in the current session (sessionid) and * attributes already set on this object. * @return The archive identifier (IID) on successful completion (returned from the OMS) * @throws OMSUploadException// ww w . j a v a 2 s. co m */ public String uploadPub() throws OMSUploadException { String msg = ""; try { URL url = null; HttpURLConnection urlConn = null; // URL of servlet. url = new URL(this.url); // URL connection channel. urlConn = getConnection(url, 5); // Let the run-time system (RTS) know that we want input. urlConn.setDoInput(true); urlConn.setRequestProperty("Content-Type", "application/octet-stream"); urlConn.setRequestProperty("Content-Length", "0"); urlConn.setRequestProperty("sessionid", sessionId); urlConn.setRequestMethod("POST"); urlConn.setRequestProperty("upload-object", "true"); urlConn.setRequestProperty("referenceNumber", referenceNumber); urlConn.setRequestProperty("ilsTapuhiFlag", ilsTapuhiFlag); urlConn.setRequestProperty("collectionType", collectionType); urlConn.setRequestProperty("objectType", objectType); urlConn.setRequestProperty("accessRestriction", accessRestriction); if (restrictionDate != null) { urlConn.setRequestProperty("restrictionDate", dateFormatter.format(restrictionDate)); } urlConn.setRequestProperty("restrictionNarrative", restrictionNarrative); urlConn.setRequestProperty("agencyResponsible", agencyResponsible); urlConn.setRequestProperty("alternativeReferenceNumber", alternativeReferenceNumber); urlConn.setRequestProperty("sourceType", sourceType); urlConn.setRequestProperty("digitisationReason", digitisationReason); urlConn.setRequestProperty("instanceRole", instanceRole); urlConn.setRequestProperty("isAccessAvailable", Boolean.toString(isAccessAvailable)); urlConn.setRequestProperty("instanceCaptureSystem", instanceCaptureSystem); urlConn.setRequestProperty("personResponsible", personResponsible); urlConn.setRequestProperty("maintenanceFlag", Boolean.toString(maintenanceFlag)); urlConn.setRequestProperty("inMaintenanceNotes", inMaintenanceNotes); urlConn.setRequestProperty("inNotes", inNotes); urlConn.setRequestProperty("inDependencies", inDependencies); urlConn.setRequestProperty("inEntryPointURL", inEntryPointURL); urlConn.setRequestProperty("unixNonCompliantFlag", Boolean.toString(unixNonCompliantFlag)); urlConn.setRequestProperty("instanceType", instanceType); urlConn.setRequestProperty("inFileDirectory", inFileDirectory); urlConn.setRequestProperty("user", user); urlConn.setRequestProperty("usersGroup", Integer.toString(usersGroup)); urlConn.setRequestProperty("user_group", Integer.toString(user_group)); // Get response data. BufferedReader input = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); msg = urlConn.getHeaderField("oms-iid"); input.close(); urlConn.disconnect(); if (msg == null) { throw new OMSUploadException("Upload failed - expected an oms-iid header in the reutrn from OMS"); } } catch (Exception e) { msg = "Error: " + e.getMessage(); throw new OMSUploadException(e); } return msg; }
From source file:com.wavemaker.runtime.service.WaveMakerService.java
public String remoteRESTCall(String remoteURL, String params, String method, String contentType) { proxyCheck(remoteURL);/*from w w w . ja v a 2 s . c o m*/ String charset = "UTF-8"; StringBuffer returnString = new StringBuffer(); try { if (method.toLowerCase().equals("put") || method.toLowerCase().equals("post") || params == null || params.equals("")) { } else { if (remoteURL.indexOf("?") != -1) { remoteURL += "&" + params; } else { remoteURL += "?" + params; } } URL url = new URL(remoteURL); if (this.logger.isDebugEnabled()) { this.logger.debug("Opening URL: " + url); } HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod(method); connection.setDoInput(true); connection.setRequestProperty("Accept-Charset", "application/json"); connection.setRequestProperty("Accept-Encoding", "text/plain"); connection.setRequestProperty("Content-Language", charset); connection.setRequestProperty("Content-Type", contentType); connection.setRequestProperty("Transfer-Encoding", "identity"); connection.setUseCaches(false); HttpServletRequest request = RuntimeAccess.getInstance().getRequest(); Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String name = headerNames.nextElement(); Enumeration<String> headers = request.getHeaders(name); if (headers != null && !name.toLowerCase().equals("accept-encoding") && !name.toLowerCase().equals("accept-charset") && !name.toLowerCase().equals("content-type")) { while (headers.hasMoreElements()) { String headerValue = headers.nextElement(); connection.setRequestProperty(name, headerValue); if (this.logger.isDebugEnabled()) { this.logger.debug("HEADER: " + name + ": " + headerValue); } } } } // Re-wrap single quotes into double quotes String finalParams; if (contentType.toLowerCase().equals("application/json")) { finalParams = params.replace("\'", "\""); if (!method.toLowerCase().equals("post") && !method.toLowerCase().equals("put") && method != null && !method.equals("")) { URLEncoder.encode(finalParams, charset); } } else { finalParams = params; } connection.setRequestProperty("Content-Length", "" + Integer.toString(finalParams.getBytes().length)); // set payload if (method.toLowerCase().equals("post") || method.toLowerCase().equals("put") || method == null || method.equals("")) { DataOutputStream writer = new DataOutputStream(connection.getOutputStream()); writer.writeBytes(finalParams); writer.flush(); writer.close(); } InputStream response = connection.getInputStream(); BufferedReader reader = null; int responseLen = 0; try { int i = 0; String field; HttpServletResponse wmResponse = RuntimeAccess.getInstance().getResponse(); while ((field = connection.getHeaderField(i)) != null) { String key = connection.getHeaderFieldKey(i); if (key == null || field == null) { } else { if (key.toLowerCase().equals("proxy-connection") || key.toLowerCase().equals("expires")) { logger.debug("Remote server returned header of: " + key + " " + field + " it was not forwarded"); } else if (key.toLowerCase().equals("transfer-encoding") && field.toLowerCase().equals("chunked")) { logger.debug("Remote server returned header of: " + key + " " + field + " it was not forwarded"); } else if (key.toLowerCase().equals("content-length")) { // do NOT use this length as return header value responseLen = new Integer(field); } else { wmResponse.addHeader(key, field); } } i++; } reader = new BufferedReader(new InputStreamReader(response, charset)); for (String line; (line = reader.readLine()) != null;) { returnString.append(line); } } finally { if (reader != null) { try { reader.close(); } catch (Exception e) { } } } connection.disconnect(); return returnString.toString(); } catch (Exception e) { logger.error("ERROR in XHR proxy call: " + e.getMessage()); throw new WMRuntimeException(e); } }