List of usage examples for java.net HttpURLConnection getHeaderFields
public Map<String, List<String>> getHeaderFields()
From source file:org.runnerup.export.GarminSynchronizer.java
private Status connectNew() throws MalformedURLException, IOException, JSONException { Status s = Status.NEED_AUTH;/*from w w w . j a v a 2 s .com*/ s.authMethod = Synchronizer.AuthMethod.USER_PASS; FormValues fv = new FormValues(); fv.put("service", "https://connect.garmin.com/post-auth/login"); fv.put("clientId", "GarminConnect"); fv.put("consumeServiceTicket", "false"); HttpURLConnection conn = get("https://sso.garmin.com/sso/login", fv); addCookies(conn); expectResponse(conn, 200, "Connection 1: "); getCookies(conn); getFormValues(conn); conn.disconnect(); // try again FormValues data = new FormValues(); data.put("username", username); data.put("password", password); data.put("_eventId", "submit"); data.put("embed", "true"); data.put("lt", formValues.get("lt")); conn = post("https://sso.garmin.com/sso/login", fv); conn.setInstanceFollowRedirects(false); conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); addCookies(conn); SyncHelper.postData(conn, data); expectResponse(conn, 200, "Connection 2: "); getCookies(conn); String html = getFormValues(conn); conn.disconnect(); /* this is really horrible */ int start = html.indexOf("?ticket="); if (start == -1) { throw new IOException("Invalid login, unable to locate ticket"); } start += "?ticket=".length(); int end = html.indexOf("'", start); String ticket = html.substring(start, end); Log.e(getName(), "ticket: " + ticket); // connection 3... fv.clear(); fv.put("ticket", ticket); conn = get("https://connect.garmin.com/post-auth/login", fv); conn.setInstanceFollowRedirects(false); addCookies(conn); for (int i = 0;; i++) { int code = conn.getResponseCode(); Log.e(getName(), "attempt: " + i + " => code: " + code); getCookies(conn); if (code == HttpStatus.SC_OK) break; if (code != HttpStatus.SC_MOVED_TEMPORARILY) break; List<String> fields = conn.getHeaderFields().get("location"); conn.disconnect(); conn = get(fields.get(0), null); conn.setInstanceFollowRedirects(false); addCookies(conn); } conn.disconnect(); return Status.OK; // return checkLogin(); }
From source file:org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest.java
public RestResponse httpSendPostWithAuth(String url, String body, Map<String, String> headers, String username, String password) throws IOException { String userPassword = username + ":" + password; String encoding = Base64.encodeBase64String(userPassword.getBytes()); RestResponse restResponse = new RestResponse(); URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // add request method con.setRequestMethod("POST"); con.setRequestProperty("Authorization", "Basic " + encoding); // add request headers if (headers != null) { for (Entry<String, String> header : headers.entrySet()) { String key = header.getKey(); String value = header.getValue(); con.setRequestProperty(key, value); }//from www. j a v a 2 s. c o m } // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(body); wr.flush(); wr.close(); // con.connect(); int responseCode = con.getResponseCode(); logger.debug("Send POST http request, url: {}", url); logger.debug("Response Code: {}", responseCode); StringBuffer response = new StringBuffer(); try { BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); } catch (Exception e) { response = null; } logger.debug("Response body: {}", response); // print result restResponse.setErrorCode(responseCode); if (response == null) { restResponse.setResponse(null); } else { restResponse.setResponse(response.toString()); } Map<String, List<String>> headerFields = con.getHeaderFields(); restResponse.setHeaderFields(headerFields); String responseMessage = con.getResponseMessage(); restResponse.setResponseMessage(responseMessage); con.disconnect(); return restResponse; }
From source file:org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest.java
public RestResponse httpSendPostWithOutBody(String url, Map<String, String> headers) throws IOException { RestResponse restResponse = new RestResponse(); URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // add request method con.setRequestMethod("POST"); // add request headers if (headers != null) { for (Entry<String, String> header : headers.entrySet()) { String key = header.getKey(); String value = header.getValue(); con.setRequestProperty(key, value); }/*from w w w .j a v a 2 s . co m*/ } // con.connect(); int responseCode = con.getResponseCode(); logger.debug("Send POST http request, url: {}", url); logger.debug("Response Code: {}", responseCode); StringBuffer response = new StringBuffer(); try { BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); } catch (Exception e) { // response = null; logger.debug("response body is null"); } String result; try { result = IOUtils.toString(con.getErrorStream()); response.append(result); } catch (Exception e2) { result = null; } logger.debug("Response body: {}", response); // print result restResponse.setErrorCode(responseCode); // if (response == null) { // restResponse.setResponse(null); // } else { // restResponse.setResponse(response.toString()); // } if (response != null) { restResponse.setResponse(response.toString()); } Map<String, List<String>> headerFields = con.getHeaderFields(); restResponse.setHeaderFields(headerFields); String responseMessage = con.getResponseMessage(); restResponse.setResponseMessage(responseMessage); con.disconnect(); return restResponse; }
From source file:org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest.java
public RestResponse httpSendDeleteWithBody(String url, String body, Map<String, String> headers) throws IOException { RestResponse restResponse = new RestResponse(); URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // add request method con.setRequestMethod("DELETE"); // add request headers if (headers != null) { for (Entry<String, String> header : headers.entrySet()) { String key = header.getKey(); String value = header.getValue(); con.setRequestProperty(key, value); }//from w w w .jav a 2s .com } // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(body); wr.flush(); wr.close(); // con.connect(); int responseCode = con.getResponseCode(); logger.debug("Send DELETE http request, url: {}", url); logger.debug("Response Code: {}", responseCode); StringBuffer response = new StringBuffer(); try { BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); } catch (Exception e) { logger.debug("response body is null"); } String result; try { result = IOUtils.toString(con.getErrorStream()); response.append(result); } catch (Exception e2) { result = null; } logger.debug("Response body: {}", response); // print result restResponse.setErrorCode(responseCode); if (response != null) { restResponse.setResponse(response.toString()); } Map<String, List<String>> headerFields = con.getHeaderFields(); restResponse.setHeaderFields(headerFields); String responseMessage = con.getResponseMessage(); restResponse.setResponseMessage(responseMessage); con.disconnect(); return restResponse; }
From source file:io.wittmann.jiralist.servlet.ProxyServlet.java
/** * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) *//*from ww w. ja va2 s . c om*/ @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.openecomp.sdc.ci.tests.datatypes.http.HttpRequest.java
public RestResponse sendHttpPost(String url, String body, Map<String, String> headers) throws IOException { RestResponse restResponse = new RestResponse(); URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // add request method con.setRequestMethod("POST"); // add request headers if (headers != null) { for (Entry<String, String> header : headers.entrySet()) { String key = header.getKey(); String value = header.getValue(); con.setRequestProperty(key, value); }//from ww w . jav a2 s . c om } // Send post request if (body != null) { con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(body); wr.flush(); wr.close(); } // con.connect(); int responseCode = con.getResponseCode(); logger.debug("Send POST http request, url: {}", url); logger.debug("Response Code: {}", responseCode); StringBuffer response = new StringBuffer(); try { BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); } catch (Exception e) { logger.debug("response body is null"); } String result; try { result = IOUtils.toString(con.getErrorStream()); response.append(result); } catch (Exception e2) { result = null; } logger.debug("Response body: {}", response); // print result restResponse.setErrorCode(responseCode); if (response != null) { restResponse.setResponse(response.toString()); } Map<String, List<String>> headerFields = con.getHeaderFields(); restResponse.setHeaderFields(headerFields); String responseMessage = con.getResponseMessage(); restResponse.setResponseMessage(responseMessage); con.disconnect(); return restResponse; }
From source file:org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest.java
public RestResponse httpSendPost(String url, String body, Map<String, String> headers, String methodType) throws IOException { RestResponse restResponse = new RestResponse(); URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // add request method con.setRequestMethod(methodType);/*from w w w . j a v a 2s.c o m*/ // add request headers if (headers != null) { for (Entry<String, String> header : headers.entrySet()) { String key = header.getKey(); String value = header.getValue(); con.setRequestProperty(key, value); } } // Send post request if (body != null) { con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(body); wr.flush(); wr.close(); } // con.connect(); int responseCode = con.getResponseCode(); logger.debug("Send POST http request, url: {}", url); logger.debug("Response Code: {}", responseCode); StringBuffer response = new StringBuffer(); try { BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); } catch (Exception e) { logger.debug("response body is null"); } String result; try { result = IOUtils.toString(con.getErrorStream()); response.append(result); } catch (Exception e2) { result = null; } logger.debug("Response body: {}", response); // print result restResponse.setErrorCode(responseCode); if (response != null) { restResponse.setResponse(response.toString()); } Map<String, List<String>> headerFields = con.getHeaderFields(); restResponse.setHeaderFields(headerFields); String responseMessage = con.getResponseMessage(); restResponse.setResponseMessage(responseMessage); con.disconnect(); return restResponse; }
From source file:org.ramadda.util.Utils.java
/** * _more_/*from w ww . jav a2 s. c o m*/ * * @param url _more_ * @param args _more_ * * @return _more_ * * @throws Exception _more_ */ public static String doGet(URL url, String... args) throws Exception { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // connection.setDoOutput(true); // connection.setDoInput(true); // connection.setInstanceFollowRedirects(false); connection.setRequestMethod("GET"); // connection.setRequestProperty("charset", "utf-8"); for (int i = 0; i < args.length; i += 2) { //System.err.println(args[i]+":" + args[i+1]); connection.setRequestProperty(args[i], args[i + 1]); } try { BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); StringBuilder sb = new StringBuilder(); String line; while ((line = in.readLine()) != null) { sb.append(line); sb.append("\n"); } return sb.toString(); } catch (Exception exc) { System.err.println("Error:" + connection.getResponseCode()); System.err.println(connection.getHeaderFields()); throw exc; // System.err.println(connection.getContent()); } }
From source file:com.centurylink.mdw.util.HttpHelper.java
/** * Populates the response member. Closes the connection. *///from w ww. j ava 2 s . c o m private void readInput(HttpURLConnection connection) throws IOException { InputStream is = null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { byte[] buffer = new byte[2048]; try { is = connection.getInputStream(); while (maxBytes == -1 || baos.size() < maxBytes) { int bytesRead = is.read(buffer); if (bytesRead == -1) break; baos.write(buffer, 0, bytesRead); } response = baos.toByteArray(); if (followHtmlHeadMetaRefresh && getResponse().indexOf("http-equiv") > 0) { try { redirect = parseResponseForHtmlMetaEquiv(getResponse()); if (redirect != null) response = new HttpHelper(this, redirect).getBytes(); } catch (Exception ex) { throw new IllegalArgumentException("Unparseable response: " + ex.getMessage(), ex); } } } catch (IOException ex) { InputStream eis = null; try { eis = connection.getErrorStream(); while (maxBytes == -1 || baos.size() < maxBytes) { int bytesRead = eis.read(buffer); if (bytesRead == -1) break; baos.write(buffer, 0, bytesRead); } response = baos.toByteArray(); } catch (Exception ex2) { // throw original exception } finally { if (eis != null) { eis.close(); } } throw ex; } } finally { if (is != null) is.close(); connection.disconnect(); responseCode = connection.getResponseCode(); responseMessage = connection.getResponseMessage(); headers = new HashMap<String, String>(); for (String headerKey : connection.getHeaderFields().keySet()) { if (headerKey == null) headers.put("HTTP", connection.getHeaderField(headerKey)); else headers.put(headerKey, connection.getHeaderField(headerKey)); } } }
From source file:org.ramadda.util.Utils.java
/** * _more_/*from w w w.ja v a 2 s. com*/ * * @param action _more_ * @param url _more_ * @param body _more_ * @param args _more_ * * @return _more_ * * @throws Exception _more_ */ public static String doHttpRequest(String action, URL url, String body, String... args) throws Exception { // URL url = new URL(request); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setInstanceFollowRedirects(false); connection.setRequestMethod(action); connection.setRequestProperty("charset", "utf-8"); for (int i = 0; i < args.length; i += 2) { // System.err.println(args[i]+":" + args[i+1]); connection.setRequestProperty(args[i], args[i + 1]); } if (body != null) { connection.setRequestProperty("Content-Length", Integer.toString(body.length())); connection.getOutputStream().write(body.getBytes()); } try { return readString(new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"))); } catch (Exception exc) { System.err.println("Utils: error doing http request:" + action + "\nURL:" + url + "\nreturn code:" + connection.getResponseCode() + "\nBody:" + body); System.err.println(readError(connection)); System.err.println(connection.getHeaderFields()); throw exc; // System.err.println(connection.getContent()); } }