List of usage examples for java.net HttpURLConnection addRequestProperty
public void addRequestProperty(String key, String value)
From source file:com.sun.socialsite.web.rest.servlets.ProxyServlet.java
/** * Handles the HTTP <code>GET</code> method. * @param req servlet request//w w w.j ava 2 s .c o m * @param resp servlet response */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { URL url = getURL(req, req.getParameter("uri")); HttpURLConnection con = (HttpURLConnection) (url.openConnection()); con.setAllowUserInteraction(false); con.setUseCaches(false); // TODO: figure out why this is necessary for HTTPS URLs if (con instanceof HttpsURLConnection) { HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) { if ("localhost".equals(urlHostName) && "127.0.0.1".equals(session.getPeerHost())) { return true; } else { log.error("URL Host: " + urlHostName + " vs. " + session.getPeerHost()); return false; } } }; ((HttpsURLConnection) con).setDefaultHostnameVerifier(hv); } // pass along all appropriate HTTP headers Enumeration headerNames = req.getHeaderNames(); while (headerNames.hasMoreElements()) { String hname = (String) headerNames.nextElement(); if (!unproxiedHeaders.contains(hname.toLowerCase())) { con.addRequestProperty(hname, req.getHeader(hname)); } } con.connect(); // read result headers of GET, write to response Map<String, List<String>> headers = con.getHeaderFields(); for (String key : headers.keySet()) { if (key != null) { // TODO: why is this check necessary! List<String> header = headers.get(key); if (header.size() > 0) resp.setHeader(key, header.get(0)); } } InputStream in = con.getInputStream(); OutputStream out = resp.getOutputStream(); final byte[] buf = new byte[8192]; int len; while ((len = in.read(buf)) != -1) { out.write(buf, 0, len); } out.flush(); } catch (Exception e) { throw new ServletException(e); } }
From source file:iracing.webapi.IracingWebApi.java
public String[] getUserData() throws IOException, LoginException { //if ((cookie == null) || (cookie.matches("^\\s*$"))) { if (!cookieMap.containsKey(JSESSIONID)) { // logger.warn("Cookie is " + cookie + ", performing login to get new cookie"); if (login() != LoginResponse.Success) { System.err.println("Login failed"); return null; }//from w w w .j a v a 2 s.com } URL url = new URL(DRIVER_PROFILE_URL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.addRequestProperty(COOKIE, cookie); // logger.debug("opening connection to " + url.getFile()); conn.connect(); if (isMaintenancePage(conn)) return null; String pageData = ""; String custid = null; String friends = null; String studied = null; BufferedReader b = new BufferedReader(new InputStreamReader(conn.getInputStream())); try { boolean found = false; while (!found && (pageData = b.readLine()) != null) { // logger.debug("line received : " + pageData); if (pageData.contains("this.currentCustId = ")) { // logger.debug("found CustId in this line, attempting extract"); int x = pageData.indexOf("this.currentCustId = "); int y = pageData.indexOf(";"); custid = pageData.substring(x + 21, y); // logger.debug("following extract, saving CustId as " + custid); found = true; } else if (pageData.contains("var FriendsListing")) { // logger.debug("found 'var FriendsListing' in this line, attempting extract"); int x = pageData.indexOf("{"); int y = pageData.indexOf("}"); friends = pageData.substring(x + 1, y); friends = friends.replaceAll("\"", ""); friends = friends.replaceAll(":1", ""); friends = friends.replaceAll(":2", ""); // logger.debug("Friends List (green) is " + friends + " following extract"); } else { if (!pageData.contains("var WatchedListing")) { continue; } // logger.debug("found 'var WatchedListing' in this line, attempting extract"); int x = pageData.indexOf("{"); int y = pageData.indexOf("}"); studied = pageData.substring(x + 1, y); studied = studied.replaceAll("\"", ""); studied = studied.replaceAll(":1", ""); studied = studied.replaceAll(":2", ""); // logger.debug("Watched List (blue) is " + studied + " following extract"); } } } finally { b.close(); } conn.disconnect(); return new String[] { custid, friends, studied }; }
From source file:fi.cosky.sdk.API.java
private <T extends BaseData> T sendRequest(Link l, Class<T> tClass, Object object) throws IOException { URL serverAddress;/*www .ja va 2s . co m*/ BufferedReader br; String result = ""; HttpURLConnection connection = null; String url = l.getUri().contains("://") ? l.getUri() : this.baseUrl + l.getUri(); try { String method = l.getMethod(); String type = l.getType(); serverAddress = new URL(url); connection = (HttpURLConnection) serverAddress.openConnection(); boolean doOutput = doOutput(method); connection.setDoOutput(doOutput); connection.setRequestMethod(method); connection.setInstanceFollowRedirects(false); if (method.equals("GET") && useMimeTypes) if (type == null || type.equals("")) { addMimeTypeAcceptToRequest(object, tClass, connection); } else { connection.addRequestProperty("Accept", helper.getSupportedType(type)); } if (!useMimeTypes) connection.setRequestProperty("Accept", "application/json"); if (doOutput && useMimeTypes) { //this handles the case if the link is self made and the type field has not been set. if (type == null || type.equals("")) { addMimeTypeContentTypeToRequest(l, tClass, connection); addMimeTypeAcceptToRequest(l, tClass, connection); } else { connection.addRequestProperty("Accept", helper.getSupportedType(type)); connection.addRequestProperty("Content-Type", helper.getSupportedType(type)); } } if (!useMimeTypes) connection.setRequestProperty("Content-Type", "application/json"); if (tokenData != null) { connection.addRequestProperty("Authorization", tokenData.getTokenType() + " " + tokenData.getAccessToken()); } addVersionNumberToHeader(object, url, connection); if (method.equals("POST") || method.equals("PUT")) { String json = object != null ? gson.toJson(object) : ""; //should handle the case when POST without object. connection.addRequestProperty("Content-Length", json.getBytes("UTF-8").length + ""); OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream()); osw.write(json); osw.flush(); osw.close(); } connection.connect(); if (connection.getResponseCode() == HttpURLConnection.HTTP_CREATED || connection.getResponseCode() == HttpURLConnection.HTTP_SEE_OTHER) { ResponseData data = new ResponseData(); Link link = parseLocationLinkFromString(connection.getHeaderField("Location")); link.setType(type); data.setLocation(link); connection.disconnect(); return (T) data; } if (connection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { System.out.println( "Authentication expired " + connection.getResponseMessage() + " trying to reauthenticate"); if (retry && this.tokenData != null) { this.tokenData = null; retry = false; if (authenticate()) { System.out.println("Reauthentication success, will continue with " + l.getMethod() + " request on " + l.getRel()); return sendRequest(l, tClass, object); } } else throw new IOException( "Tried to reauthenticate but failed, please check the credentials and status of NFleet-API"); } if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) { return (T) objectCache.getObject(url); } if (connection.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT) { return (T) new ResponseData(); } if (connection.getResponseCode() >= HttpURLConnection.HTTP_BAD_REQUEST && connection.getResponseCode() < HttpURLConnection.HTTP_INTERNAL_ERROR) { System.out.println("ErrorCode: " + connection.getResponseCode() + " " + connection.getResponseMessage() + " " + url + ", verb: " + method); String errorString = readErrorStreamAndCloseConnection(connection); throw (NFleetRequestException) gson.fromJson(errorString, NFleetRequestException.class); } else if (connection.getResponseCode() >= HttpURLConnection.HTTP_INTERNAL_ERROR) { if (retry) { System.out.println("Request caused internal server error, waiting " + RETRY_WAIT_TIME + " ms and trying again."); return waitAndRetry(connection, l, tClass, object); } else { System.out.println("Requst caused internal server error, please contact dev@nfleet.fi"); String errorString = readErrorStreamAndCloseConnection(connection); throw new IOException(errorString); } } if (connection.getResponseCode() >= HttpURLConnection.HTTP_BAD_GATEWAY) { if (retry) { System.out.println("Could not connect to NFleet-API, waiting " + RETRY_WAIT_TIME + " ms and trying again."); return waitAndRetry(connection, l, tClass, object); } else { System.out.println( "Could not connect to NFleet-API, please check service status from http://status.nfleet.fi and try again later."); String errorString = readErrorStreamAndCloseConnection(connection); throw new IOException(errorString); } } result = readDataFromConnection(connection); } catch (MalformedURLException e) { throw e; } catch (ProtocolException e) { throw e; } catch (UnsupportedEncodingException e) { throw e; } catch (IOException e) { throw e; } catch (SecurityException e) { throw e; } catch (IllegalArgumentException e) { throw e; } finally { assert connection != null; connection.disconnect(); } Object newEntity = gson.fromJson(result, tClass); objectCache.addUri(url, newEntity); return (T) newEntity; }
From source file:export.GarminUploader.java
private Status connectOld() throws MalformedURLException, IOException, JSONException { Status s = Status.NEED_AUTH;/*from w w w. ja v a2 s. c o m*/ s.authMethod = Uploader.AuthMethod.USER_PASS; HttpURLConnection conn = null; /** * connect to START_URL to get cookies */ conn = (HttpURLConnection) new URL(START_URL).openConnection(); { int responseCode = conn.getResponseCode(); String amsg = conn.getResponseMessage(); getCookies(conn); if (responseCode != 200) { System.err.println("GarminUploader::connect() - got " + responseCode + ", msg: " + amsg); } } conn.disconnect(); /** * Then login using a post */ String login = LOGIN_URL; FormValues kv = new FormValues(); kv.put("login", "login"); kv.put("login:loginUsernameField", username); kv.put("login:password", password); kv.put("login:signInButton", "Sign In"); kv.put("javax.faces.ViewState", "j_id1"); conn = (HttpURLConnection) new URL(login).openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); addCookies(conn); { OutputStream wr = new BufferedOutputStream(conn.getOutputStream()); kv.write(wr); wr.flush(); wr.close(); int responseCode = conn.getResponseCode(); String amsg = conn.getResponseMessage(); System.err.println("code: " + responseCode + ", msg=" + amsg); getCookies(conn); } conn.disconnect(); /** * An finally check that all is OK */ return checkLogin(); }
From source file:org.jmxtrans.embedded.output.CopperEggWriter.java
public String Send_Commmand(String command, String msgtype, String payload, Integer ExpectInt) { HttpURLConnection urlConnection = null; URL myurl = null;/* w ww . j a v a2s . c o m*/ OutputStreamWriter wr = null; int responseCode = 0; String id = null; int error = 0; try { myurl = new URL(url_str + command); urlConnection = (HttpURLConnection) myurl.openConnection(); urlConnection.setRequestMethod(msgtype); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setReadTimeout(coppereggApiTimeoutInMillis); urlConnection.addRequestProperty("User-Agent", "Mozilla/4.76"); urlConnection.setRequestProperty("content-type", "application/json; charset=utf-8"); urlConnection.setRequestProperty("Authorization", "Basic " + basicAuthentication); wr = new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8"); wr.write(payload); wr.flush(); responseCode = urlConnection.getResponseCode(); if (responseCode != 200) { logger.warn( "Send Command: Response code " + responseCode + " url is " + myurl + " command " + msgtype); error = 1; } } catch (Exception e) { exceptionCounter.incrementAndGet(); logger.warn("Exception in Send Command: url is " + myurl + " command " + msgtype + "; " + e); error = 1; } finally { if (urlConnection != null) { try { if (error > 0) { InputStream err = urlConnection.getErrorStream(); String errString = convertStreamToString(err); logger.warn("Reported error : " + errString); IoUtils2.closeQuietly(err); } else { InputStream in = urlConnection.getInputStream(); String theString = convertStreamToString(in); id = jparse(theString, ExpectInt); IoUtils2.closeQuietly(in); } } catch (IOException e) { exceptionCounter.incrementAndGet(); logger.warn("Exception in Send Command : flushing http connection " + e); } } if (wr != null) { try { wr.close(); } catch (IOException e) { exceptionCounter.incrementAndGet(); logger.warn("Exception in Send Command: closing OutputWriter " + e); } } } return (id); }
From source file:org.alfresco.mobile.android.api.network.NetworkHttpInvoker.java
protected Response invoke(UrlBuilder url, String method, String contentType, Map<String, String> headers, Output writer, BindingSession session, BigInteger offset, BigInteger length) { try {//from ww w. j ava 2 s .c om // log before connect //Log.d("URL", url.toString()); if (LOG.isDebugEnabled()) { LOG.debug(method + " " + url); } // connect HttpURLConnection conn = getHttpURLConnection(new URL(url.toString())); conn.setRequestMethod(method); conn.setDoInput(true); conn.setDoOutput(writer != null); conn.setAllowUserInteraction(false); conn.setUseCaches(false); conn.setRequestProperty(HTTP.USER_AGENT, ClientVersion.OPENCMIS_CLIENT); // timeouts int connectTimeout = session.get(SessionParameter.CONNECT_TIMEOUT, -1); if (connectTimeout >= 0) { conn.setConnectTimeout(connectTimeout); } int readTimeout = session.get(SessionParameter.READ_TIMEOUT, -1); if (readTimeout >= 0) { conn.setReadTimeout(readTimeout); } // set content type if (contentType != null) { conn.setRequestProperty(HTTP.CONTENT_TYPE, contentType); } // set other headers if (headers != null) { for (Map.Entry<String, String> header : headers.entrySet()) { conn.addRequestProperty(header.getKey(), header.getValue()); } } // authenticate AuthenticationProvider authProvider = CmisBindingsHelper.getAuthenticationProvider(session); if (authProvider != null) { Map<String, List<String>> httpHeaders = authProvider.getHTTPHeaders(url.toString()); if (httpHeaders != null) { for (Map.Entry<String, List<String>> header : httpHeaders.entrySet()) { if (header.getValue() != null) { for (String value : header.getValue()) { conn.addRequestProperty(header.getKey(), value); } } } } if (conn instanceof HttpsURLConnection) { SSLSocketFactory sf = authProvider.getSSLSocketFactory(); if (sf != null) { ((HttpsURLConnection) conn).setSSLSocketFactory(sf); } HostnameVerifier hv = authProvider.getHostnameVerifier(); if (hv != null) { ((HttpsURLConnection) conn).setHostnameVerifier(hv); } } } // range if ((offset != null) || (length != null)) { StringBuilder sb = new StringBuilder("bytes="); if ((offset == null) || (offset.signum() == -1)) { offset = BigInteger.ZERO; } sb.append(offset.toString()); sb.append("-"); if ((length != null) && (length.signum() == 1)) { sb.append(offset.add(length.subtract(BigInteger.ONE)).toString()); } conn.setRequestProperty("Range", sb.toString()); } // compression Object compression = session.get(AlfrescoSession.HTTP_ACCEPT_ENCODING); if (compression == null) { conn.setRequestProperty("Accept-Encoding", ""); } else { Boolean compressionValue; try { compressionValue = Boolean.parseBoolean(compression.toString()); if (compressionValue) { conn.setRequestProperty("Accept-Encoding", "gzip,deflate"); } else { conn.setRequestProperty("Accept-Encoding", ""); } } catch (Exception e) { conn.setRequestProperty("Accept-Encoding", compression.toString()); } } // locale if (session.get(AlfrescoSession.HTTP_ACCEPT_LANGUAGE) instanceof String && session.get(AlfrescoSession.HTTP_ACCEPT_LANGUAGE) != null) { conn.setRequestProperty("Accept-Language", session.get(AlfrescoSession.HTTP_ACCEPT_LANGUAGE).toString()); } // send data if (writer != null) { Object chunkTransfert = session.get(AlfrescoSession.HTTP_CHUNK_TRANSFERT); if (chunkTransfert != null && Boolean.parseBoolean(chunkTransfert.toString())) { conn.setRequestProperty(HTTP.TRANSFER_ENCODING, "chunked"); conn.setChunkedStreamingMode(0); } conn.setConnectTimeout(900000); OutputStream connOut = null; Object clientCompression = session.get(SessionParameter.CLIENT_COMPRESSION); if ((clientCompression != null) && Boolean.parseBoolean(clientCompression.toString())) { conn.setRequestProperty(HTTP.CONTENT_ENCODING, "gzip"); connOut = new GZIPOutputStream(conn.getOutputStream(), 4096); } else { connOut = conn.getOutputStream(); } OutputStream out = new BufferedOutputStream(connOut, BUFFER_SIZE); writer.write(out); out.flush(); } // connect conn.connect(); // get stream, if present int respCode = conn.getResponseCode(); InputStream inputStream = null; if ((respCode == HttpStatus.SC_OK) || (respCode == HttpStatus.SC_CREATED) || (respCode == HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION) || (respCode == HttpStatus.SC_PARTIAL_CONTENT)) { inputStream = conn.getInputStream(); } // log after connect if (LOG.isTraceEnabled()) { LOG.trace(method + " " + url + " > Headers: " + conn.getHeaderFields()); } // forward response HTTP headers if (authProvider != null) { authProvider.putResponseHeaders(url.toString(), respCode, conn.getHeaderFields()); } // get the response return new Response(respCode, conn.getResponseMessage(), conn.getHeaderFields(), inputStream, conn.getErrorStream()); } catch (Exception e) { throw new CmisConnectionException("Cannot access " + url + ": " + e.getMessage(), e); } }
From source file:org.runnerup.export.Endomondo.java
@Override public Status upload(SQLiteDatabase db, long mID) { Status s;/*from w w w . java2 s. c o m*/ if ((s = connect()) != Status.OK) { return s; } EndomondoTrack tcx = new EndomondoTrack(db); HttpURLConnection conn = null; Exception ex = null; try { EndomondoTrack.Summary summary = new EndomondoTrack.Summary(); StringWriter writer = new StringWriter(); tcx.export(mID, writer, summary); String workoutId = deviceId + "-" + Long.toString(mID); System.err.println("workoutId: " + workoutId); StringBuilder url = new StringBuilder(); url.append(UPLOAD_URL).append("?authToken=").append(authToken); url.append("&workoutId=").append(workoutId); url.append("&sport=").append(summary.sport); url.append("&duration=").append(summary.duration); url.append("&distance=").append(summary.distance); if (summary.hr != null) { url.append("&heartRateAvg=").append(summary.hr.toString()); } url.append("&gzip=true"); url.append("&extendedResponse=true"); conn = (HttpURLConnection) new URL(url.toString()).openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.addRequestProperty("Content-Type", "application/octet-stream"); OutputStream out = new GZIPOutputStream(new BufferedOutputStream(conn.getOutputStream())); out.write(writer.getBuffer().toString().getBytes()); out.flush(); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); JSONObject res = parseKVP(in); conn.disconnect(); System.err.println("res: " + res.toString()); int responseCode = conn.getResponseCode(); String amsg = conn.getResponseMessage(); if (responseCode == 200 && "OK".contentEquals(res.getString("_0"))) { return Status.OK; } ex = new Exception(amsg); } catch (IOException e) { ex = e; } catch (JSONException e) { ex = e; } s = Uploader.Status.ERROR; s.ex = ex; if (ex != null) { ex.printStackTrace(); } return s; }