List of usage examples for java.net HttpURLConnection addRequestProperty
public void addRequestProperty(String key, String value)
From source file:org.runnerup.export.NikePlusSynchronizer.java
@Override public Status connect() { if (now() > expires_timeout) { access_token = null;/*from w w w . j a v a 2s. c om*/ } if (access_token != null) { return Status.OK; } Status s = Status.NEED_AUTH; s.authMethod = Synchronizer.AuthMethod.USER_PASS; if (username == null || password == null) { return s; } HttpURLConnection conn = null; try { /** * get user id/key */ String url = String.format(LOGIN_URL, CLIENT_ID, CLIENT_SECRET, APP_ID); conn = (HttpURLConnection) new URL(url).openConnection(); conn.setDoOutput(true); conn.setRequestMethod(RequestMethod.POST.name()); conn.addRequestProperty("user-agent", USER_AGENT); conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.addRequestProperty("Accept", "application/json"); FormValues kv = new FormValues(); kv.put("email", username); kv.put("password", password); { OutputStream wr = new BufferedOutputStream(conn.getOutputStream()); kv.write(wr); wr.flush(); wr.close(); String response; { BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder buf = new StringBuilder(); String line; while ((line = in.readLine()) != null) { buf.append(line); } response = buf.toString().replaceAll("<User>.*</User>", "\"\""); } JSONObject obj = SyncHelper.parse(new ByteArrayInputStream(response.getBytes())); access_token = obj.getString("access_token"); String expires = obj.getString("expires_in"); expires_timeout = now() + Long.parseLong(expires); s = Status.OK; } } catch (UnknownHostException e) { // probably no internet connection available s = Status.SKIP; } catch (Exception e) { s.ex = e; } if (conn != null) { conn.disconnect(); } if (s.ex != null) { Log.e(getClass().getSimpleName(), s.ex.getMessage()); } return s; }
From source file:org.runnerup.export.RunKeeperSynchronizer.java
public Status listActivities(List<SyncActivityItem> list) { Status s = connect();/*www. ja v a2s . co m*/ if (s != Status.OK) { return s; } String requestUrl = REST_URL + fitnessActivitiesUrl; while (requestUrl != null) { try { URL nextUrl = new URL(requestUrl); HttpURLConnection conn = (HttpURLConnection) nextUrl.openConnection(); conn.setDoInput(true); conn.setRequestMethod(RequestMethod.GET.name()); conn.addRequestProperty("Authorization", "Bearer " + access_token); conn.addRequestProperty("Content-Type", "application/vnd.com.runkeeper.FitnessActivityFeed+json"); InputStream input = new BufferedInputStream(conn.getInputStream()); if (conn.getResponseCode() == HttpStatus.SC_OK) { JSONObject resp = SyncHelper.parse(input); requestUrl = parseForNext(resp, list); s = Status.OK; } else { s = Status.ERROR; } input.close(); conn.disconnect(); } catch (IOException e) { Log.e(Constants.LOG, e.getMessage()); requestUrl = null; s = Status.ERROR; } catch (JSONException e) { Log.e(Constants.LOG, e.getMessage()); requestUrl = null; s = Status.ERROR; } } return s; }
From source file:org.exoplatform.shareextension.service.UploadAction.java
@Override protected boolean doExecute() { String id = uploadInfo.uploadId; String boundary = "----------------------------" + id; String CRLF = "\r\n"; int status = -1; OutputStream output = null;//from www. j a v a2 s. com PrintWriter writer = null; try { // Open a connection to the upload web service StringBuffer stringUrl = new StringBuffer(postInfo.ownerAccount.serverUrl).append("/portal") .append(ExoConstants.DOCUMENT_UPLOAD_PATH_REST).append("?uploadId=").append(id); URL uploadUrl = new URL(stringUrl.toString()); HttpURLConnection uploadReq = (HttpURLConnection) uploadUrl.openConnection(); uploadReq.setDoOutput(true); uploadReq.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); // Pass the session cookies for authentication CookieStore store = ExoConnectionUtils.cookiesStore; if (store != null) { StringBuffer cookieString = new StringBuffer(); for (Cookie cookie : store.getCookies()) { cookieString.append(cookie.getName()).append("=").append(cookie.getValue()).append("; "); } uploadReq.addRequestProperty("Cookie", cookieString.toString()); } ExoConnectionUtils.setUserAgent(uploadReq); // Write the form data output = uploadReq.getOutputStream(); writer = new PrintWriter(new OutputStreamWriter(output, "UTF-8"), true); writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + uploadInfo.fileToUpload.documentName + "\"").append(CRLF); writer.append("Content-Type: " + uploadInfo.fileToUpload.documentMimeType).append(CRLF); writer.append(CRLF).flush(); byte[] buf = new byte[1024]; while (uploadInfo.fileToUpload.documentData.read(buf) != -1) { output.write(buf); } output.flush(); writer.append(CRLF).flush(); writer.append("--" + boundary + "--").append(CRLF).flush(); // Execute the connection and retrieve the status code status = uploadReq.getResponseCode(); } catch (Exception e) { Log.e(LOG_TAG, "Error while uploading " + uploadInfo.fileToUpload, e); } finally { if (uploadInfo != null && uploadInfo.fileToUpload != null && uploadInfo.fileToUpload.documentData != null) try { uploadInfo.fileToUpload.documentData.close(); } catch (IOException e1) { Log.e(LOG_TAG, "Error while closing the upload stream", e1); } if (output != null) try { output.close(); } catch (IOException e) { Log.e(LOG_TAG, "Error while closing the connection", e); } if (writer != null) writer.close(); } if (status < HttpURLConnection.HTTP_OK || status >= HttpURLConnection.HTTP_MULT_CHOICE) { // Exit if the upload went wrong return listener.onError("Could not upload the file " + uploadInfo.fileToUpload.documentName); } status = -1; try { // Prepare the request to save the file in JCR String stringUrl = postInfo.ownerAccount.serverUrl + "/portal" + ExoConstants.DOCUMENT_CONTROL_PATH_REST; Uri moveUri = Uri.parse(stringUrl); moveUri = moveUri.buildUpon().appendQueryParameter("uploadId", id) .appendQueryParameter("action", "save") .appendQueryParameter("workspaceName", DocumentHelper.getInstance().workspace) .appendQueryParameter("driveName", uploadInfo.drive) .appendQueryParameter("currentFolder", uploadInfo.folder) .appendQueryParameter("fileName", uploadInfo.fileToUpload.documentName).build(); HttpGet moveReq = new HttpGet(moveUri.toString()); // Execute the request and retrieve the status code HttpResponse move = ExoConnectionUtils.httpClient.execute(moveReq); status = move.getStatusLine().getStatusCode(); } catch (Exception e) { Log.e(LOG_TAG, "Error while saving " + uploadInfo.fileToUpload + " in JCR", e); } boolean ret = false; if (status >= HttpStatus.SC_OK && status < HttpStatus.SC_MULTIPLE_CHOICES) { ret = listener.onSuccess("File " + uploadInfo.fileToUpload.documentName + "uploaded successfully"); } else { ret = listener.onError("Could not save the file " + uploadInfo.fileToUpload.documentName); } return ret; }
From source file:org.apache.jmeter.protocol.http.control.CacheManager.java
/** * Check the cache, and if there is a match, set the headers: * <ul>//from w w w . ja va 2 s . com * <li>If-Modified-Since</li> * <li>If-None-Match</li> * </ul> * @param url {@link URL} to look up in cache * @param conn where to set the headers */ public void setHeaders(HttpURLConnection conn, URL url) { CacheEntry entry = getCache().get(url.toString()); if (log.isDebugEnabled()) { log.debug(conn.getRequestMethod() + "(Java) " + url.toString() + " " + entry); } if (entry != null) { final String lastModified = entry.getLastModified(); if (lastModified != null) { conn.addRequestProperty(HTTPConstants.IF_MODIFIED_SINCE, lastModified); } final String etag = entry.getEtag(); if (etag != null) { conn.addRequestProperty(HTTPConstants.IF_NONE_MATCH, etag); } } }
From source file:org.runnerup.export.RunKeeperUploader.java
@Override public Uploader.Status upload(SQLiteDatabase db, final long mID) { Status s;// w w w. j av a2s . c om if ((s = connect()) != Status.OK) { return s; } /** * Get the fitnessActivities end-point */ HttpURLConnection conn = null; Exception ex = null; try { URL newurl = new URL(REST_URL + fitnessActivitiesUrl); System.err.println("url: " + newurl.toString()); conn = (HttpURLConnection) newurl.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.addRequestProperty("Authorization", "Bearer " + access_token); conn.addRequestProperty("Content-type", "application/vnd.com.runkeeper.NewFitnessActivity+json"); RunKeeper rk = new RunKeeper(db); BufferedWriter w = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream())); rk.export(mID, w); w.flush(); int responseCode = conn.getResponseCode(); String amsg = conn.getResponseMessage(); conn.disconnect(); conn = null; if (responseCode >= 200 && responseCode < 300) { return Uploader.Status.OK; } ex = new Exception(amsg); } catch (MalformedURLException e) { ex = e; } catch (IOException e) { ex = e; } if (ex != null) ex.printStackTrace(); if (conn != null) { conn.disconnect(); } s = Uploader.Status.ERROR; s.ex = ex; return s; }
From source file:org.runnerup.export.FunBeatSynchronizer.java
@Override public Status getFeed(FeedUpdater feedUpdater) { Status s = Status.NEED_AUTH;//from w ww.j av a2 s . c o m s.authMethod = AuthMethod.USER_PASS; if (loginID == null || loginSecretHashed == null) { if ((s = connect()) != Status.OK) { return s; } } HttpURLConnection conn = null; try { conn = (HttpURLConnection) new URL(FEED_URL).openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestMethod(RequestMethod.POST.name()); conn.addRequestProperty("Content-Type", "application/json; charset=utf-8"); final JSONObject req = getRequestObject(); final OutputStream out = new BufferedOutputStream(conn.getOutputStream()); out.write(req.toString().getBytes()); out.flush(); out.close(); final InputStream in = new BufferedInputStream(conn.getInputStream()); final JSONObject reply = SyncHelper.parse(in); final int code = conn.getResponseCode(); conn.disconnect(); if (code == HttpStatus.SC_OK) { parseFeed(feedUpdater, reply); return Status.OK; } } catch (final MalformedURLException e) { e.printStackTrace(); s.ex = e; } catch (final IOException e) { e.printStackTrace(); s.ex = e; } catch (final JSONException e) { e.printStackTrace(); s.ex = e; } s = Status.ERROR; if (conn != null) conn.disconnect(); return s; }
From source file:com.dao.ShopThread.java
private HttpURLConnection getHttpGetConn(String url) throws Exception { LogUtil.debugPrintf("getHttpGetConn url===" + url); HttpURLConnection conn; // Acts like a browser URL obj = new URL(url); conn = (HttpURLConnection) obj.openConnection(); if (null != this.cookies) { conn.addRequestProperty("Cookie", GenericUtil.cookieFormat(this.cookies)); }// ww w . ja v a2 s .c om conn.setRequestMethod("GET"); conn.setRequestProperty("User-Agent", USER_AGENT); conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); conn.setRequestProperty("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3"); conn.setRequestProperty("Accept-Encoding", "gzip, deflate"); conn.setRequestProperty("Connection", "keep-alive"); conn.setRequestProperty("Host", "consignment.5173.com"); conn.setRequestProperty("Referer", url); return conn; }
From source file:org.jetbrains.webdemo.handlers.ServerHandler.java
private void forwardRequestToBackend(HttpServletRequest request, HttpServletResponse response, Map<String, String> postParameters) { final boolean hasoutbody = (request.getMethod().equals("POST")); try {/*from w w w .ja v a2 s.c o m*/ final URL url = new URL("http://" + ApplicationSettings.BACKEND_URL + "/" + (request.getQueryString() != null ? "?" + request.getQueryString() : "")); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); final Enumeration<String> headers = request.getHeaderNames(); while (headers.hasMoreElements()) { final String header = headers.nextElement(); final Enumeration<String> values = request.getHeaders(header); while (values.hasMoreElements()) { final String value = values.nextElement(); conn.addRequestProperty(header, value); } } conn.setConnectTimeout(15000); conn.setReadTimeout(15000); conn.setUseCaches(false); conn.setDoOutput(hasoutbody); if (postParameters != null && !postParameters.isEmpty()) { conn.setRequestMethod("POST"); try (OutputStream requestBody = conn.getOutputStream()) { boolean first = true; for (Map.Entry<String, String> entry : postParameters.entrySet()) { if (entry.getValue() == null) continue; if (first) { first = false; } else { requestBody.write('&'); } requestBody.write(URLEncoder.encode(entry.getKey(), "UTF8").getBytes()); requestBody.write('='); requestBody.write(URLEncoder.encode(entry.getValue(), "UTF8").getBytes()); } } } else { conn.setRequestMethod("GET"); } StringBuilder responseBody = new StringBuilder(); if (conn.getResponseCode() >= 400) { StringBuilder serverMessage = new StringBuilder(); try (InputStream errorStream = conn.getErrorStream()) { if (errorStream != null) { byte[] buffer = new byte[1024]; while (true) { final int read = errorStream.read(buffer); if (read <= 0) break; serverMessage.append(new String(buffer, 0, read)); } } } switch (conn.getResponseCode()) { case HttpServletResponse.SC_NOT_FOUND: responseBody.append("Kotlin compile server not found"); break; case HttpServletResponse.SC_SERVICE_UNAVAILABLE: responseBody.append("Kotlin compile server is temporary overloaded"); break; default: responseBody = serverMessage; break; } } else { try (InputStream inputStream = conn.getInputStream()) { if (inputStream != null) { byte[] buffer = new byte[1024]; while (true) { final int read = inputStream.read(buffer); if (read <= 0) break; responseBody.append(new String(buffer, 0, read)); } } } } writeResponse(request, response, responseBody.toString(), conn.getResponseCode()); } catch (SocketTimeoutException e) { writeResponse(request, response, "Compile server connection timeout", HttpServletResponse.SC_GATEWAY_TIMEOUT); } catch (Exception e) { ErrorWriter.ERROR_WRITER.writeExceptionToExceptionAnalyzer(e, "FORWARD_REQUEST_TO_BACKEND", "", "Can't forward request to Kotlin compile server"); writeResponse(request, response, "Can't send your request to Kotlin compile server", HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }
From source file:org.runnerup.export.JoggSESynchronizer.java
@Override public Status connect() { if (isConnected) { return Status.OK; }//from w w w .j a v a 2 s .c o m Status s = Status.NEED_AUTH; s.authMethod = Synchronizer.AuthMethod.USER_PASS; if (username == null || password == null) { return s; } Exception ex = null; HttpURLConnection conn = null; try { /** * Login by making an empty save-gpx call and see what error message * you get Invalid/"Invalid Userdetails" => wrong user/pass * NOK/"Root element is missing" => OK */ final String LOGIN_OK = "NOK"; conn = (HttpURLConnection) new URL(BASE_URL).openConnection(); conn.setDoOutput(true); conn.setRequestMethod(RequestMethod.POST.name()); conn.addRequestProperty("Host", "jogg.se"); conn.addRequestProperty("Content-Type", "text/xml"); final BufferedWriter wr = new BufferedWriter(new PrintWriter(conn.getOutputStream())); saveGPX(wr, ""); wr.flush(); wr.close(); final InputStream in = new BufferedInputStream(conn.getInputStream()); final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); final DocumentBuilder db = dbf.newDocumentBuilder(); final InputSource is = new InputSource(); is.setByteStream(in); final Document doc = db.parse(is); conn.disconnect(); conn = null; final String path[] = { "soap:Envelope", "soap:Body", "SaveGpxResponse", "SaveGpxResult", "ResponseStatus", "ResponseCode" }; final Node e = navigate(doc, path); Log.e(getName(), "reply: " + e.getTextContent()); if (e != null && e.getTextContent() != null && LOGIN_OK.contentEquals(e.getTextContent())) { isConnected = true; return Synchronizer.Status.OK; } return s; } catch (final MalformedURLException e) { ex = e; } catch (final IOException e) { ex = e; } catch (final ParserConfigurationException e) { ex = e; } catch (final SAXException e) { ex = e; } if (conn != null) conn.disconnect(); s = Synchronizer.Status.ERROR; s.ex = ex; if (ex != null) { ex.printStackTrace(); } return s; }
From source file:org.openhab.binding.plex.internal.PlexConnector.java
private <T> T doHttpRequest(String method, String uri, Map<String, String> parameters, Class<T> type) { try {//from w w w . j ava 2 s . c o m HttpURLConnection connection = (HttpURLConnection) new URL(uri).openConnection(); connection.setRequestMethod(method); connection.setConnectTimeout(REQUEST_TIMEOUT_MS); connection.setReadTimeout(REQUEST_TIMEOUT_MS); for (Entry<String, String> entry : parameters.entrySet()) { connection.addRequestProperty(entry.getKey(), entry.getValue()); } JAXBContext jc = JAXBContext.newInstance(type); InputStream xml = connection.getInputStream(); @SuppressWarnings("unchecked") T obj = (T) jc.createUnmarshaller().unmarshal(xml); connection.disconnect(); return obj; } catch (MalformedURLException e) { logger.debug(e.getMessage(), e); } catch (IOException e) { logger.debug(e.getMessage(), e); } catch (JAXBException e) { logger.debug(e.getMessage(), e); } return null; }