List of usage examples for java.net HttpURLConnection addRequestProperty
public void addRequestProperty(String key, String value)
From source file:org.runnerup.export.GooglePlusSynchronizer.java
public Status refreshToken() { Status s = Status.OK;/*w w w. j a v a2 s.c o m*/ HttpURLConnection conn = null; final FormValues fv = new FormValues(); fv.put("client_id", getClientId()); fv.put("client_secret", getClientSecret()); fv.put("grant_type", "refresh_token"); fv.put("refresh_token", getRefreshToken()); try { URL url = new URL(getTokenUrl()); conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod(RequestMethod.POST.name()); conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); SyncHelper.postData(conn, fv); InputStream in = new BufferedInputStream(conn.getInputStream()); JSONObject obj = SyncHelper.parse(in); conn.disconnect(); access_token = obj.getString("access_token"); expire_time = obj.getLong("expires_in"); token_now = System.currentTimeMillis(); return s; } catch (MalformedURLException e) { s = Status.ERROR; s.ex = e; } catch (ProtocolException e) { s = Status.ERROR; s.ex = e; } catch (IOException e) { s = Status.ERROR; s.ex = e; } catch (JSONException e) { s.ex = e; } if (s.ex != null) s.ex.printStackTrace(); return s; }
From source file:org.apache.tez.runtime.library.shuffle.common.Fetcher.java
private HttpURLConnection connectToShuffleHandler(String host, int port, int partition, List<InputAttemptIdentifier> inputs) throws IOException { try {/* w ww.j av a2 s . c o m*/ this.url = constructInputURL(host, port, partition, inputs); HttpURLConnection connection = openConnection(url); // generate hash of the url this.msgToEncode = SecureShuffleUtils.buildMsgFrom(url); this.encHash = SecureShuffleUtils.hashFromString(msgToEncode, shuffleSecret); // put url hash into http header connection.addRequestProperty(SecureShuffleUtils.HTTP_HEADER_URL_HASH, encHash); // set the read timeout connection.setReadTimeout(readTimeout); // put shuffle version into http header connection.addRequestProperty(ShuffleHeader.HTTP_HEADER_NAME, ShuffleHeader.DEFAULT_HTTP_HEADER_NAME); connection.addRequestProperty(ShuffleHeader.HTTP_HEADER_VERSION, ShuffleHeader.DEFAULT_HTTP_HEADER_VERSION); connect(connection, connectionTimeout); return connection; } catch (IOException e) { LOG.warn("Failed to connect to " + host + " with " + srcAttempts.size() + " inputs", e); throw e; } }
From source file:org.openhab.binding.miele.internal.handler.MieleBridgeHandler.java
protected String post(URL url, Map<String, String> headers, String data) throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); if (headers != null) { for (Map.Entry<String, String> entry : headers.entrySet()) { connection.addRequestProperty(entry.getKey(), entry.getValue()); }/* w w w. j ava 2 s .c om*/ } connection.addRequestProperty("Accept-Encoding", "gzip"); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.connect(); OutputStream out = null; try { out = connection.getOutputStream(); out.write(data.getBytes()); out.flush(); int statusCode = connection.getResponseCode(); if (statusCode != HttpURLConnection.HTTP_OK) { logger.debug("An unexpected status code was returned: '{}'", statusCode); } } finally { if (out != null) { out.close(); } } String responseEncoding = connection.getHeaderField("Content-Encoding"); responseEncoding = (responseEncoding == null ? "" : responseEncoding.trim()); ByteArrayOutputStream bos = new ByteArrayOutputStream(); InputStream in = connection.getInputStream(); try { in = connection.getInputStream(); if ("gzip".equalsIgnoreCase(responseEncoding)) { in = new GZIPInputStream(in); } in = new BufferedInputStream(in); byte[] buff = new byte[1024]; int n; while ((n = in.read(buff)) > 0) { bos.write(buff, 0, n); } bos.flush(); bos.close(); } finally { if (in != null) { in.close(); } } return bos.toString(); }
From source file:export.NikePlus.java
@Override public Status connect() { if (now() > expires_timeout) { access_token = null;/* w w w .j a va 2 s. c om*/ } if (access_token != null) { return Status.OK; } Status s = Status.NEED_AUTH; s.authMethod = Uploader.AuthMethod.USER_PASS; if (username == null || password == null) { return s; } Exception ex = null; 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("POST"); 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())); StringBuffer buf = new StringBuffer(); String line; while ((line = in.readLine()) != null) { buf.append(line); } response = buf.toString().replaceAll("<User>.*</User>", "\"\""); System.err.println("buf: " + buf.toString()); System.err.println("res: " + response.toString()); } JSONObject obj = parse(new ByteArrayInputStream(response.getBytes())); conn.disconnect(); access_token = obj.getString("access_token"); String expires = obj.getString("expires_in"); expires_timeout = now() + Long.parseLong(expires); return Status.OK; } } catch (MalformedURLException e) { ex = e; } catch (IOException e) { ex = e; } catch (JSONException e) { ex = e; } if (conn != null) conn.disconnect(); s.ex = ex; if (ex != null) { ex.printStackTrace(); } return s; }
From source file:org.openhab.binding.miele.handler.MieleBridgeHandler.java
protected String post(URL url, Map<String, String> headers, String data) throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); if (headers != null) { for (Map.Entry<String, String> entry : headers.entrySet()) { connection.addRequestProperty(entry.getKey(), entry.getValue()); }/*from w w w .j a va 2s. c om*/ } connection.addRequestProperty("Accept-Encoding", "gzip"); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.connect(); OutputStream out = null; try { out = connection.getOutputStream(); out.write(data.getBytes()); out.flush(); int statusCode = connection.getResponseCode(); if (statusCode != HttpURLConnection.HTTP_OK) { logger.error("An unexpected status code was returned : '{}'", statusCode); } } finally { if (out != null) { out.close(); } } String responseEncoding = connection.getHeaderField("Content-Encoding"); responseEncoding = (responseEncoding == null ? "" : responseEncoding.trim()); ByteArrayOutputStream bos = new ByteArrayOutputStream(); InputStream in = connection.getInputStream(); try { in = connection.getInputStream(); if ("gzip".equalsIgnoreCase(responseEncoding)) { in = new GZIPInputStream(in); } in = new BufferedInputStream(in); byte[] buff = new byte[1024]; int n; while ((n = in.read(buff)) > 0) { bos.write(buff, 0, n); } bos.flush(); bos.close(); } finally { if (in != null) { in.close(); } } return bos.toString(); }
From source file:org.runnerup.export.FunBeatUploader.java
@Override public Status getFeed(FeedUpdater feedUpdater) { Status s = Status.NEED_AUTH;//from w w w. ja va2 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("POST"); 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 = parse(in); final int code = conn.getResponseCode(); conn.disconnect(); if (code == 200) { 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:org.runnerup.export.NikePlus.java
@Override public Status connect() { if (now() > expires_timeout) { access_token = null;//from w ww. j av a2 s .c om } if (access_token != null) { return Status.OK; } Status s = Status.NEED_AUTH; s.authMethod = Uploader.AuthMethod.USER_PASS; if (username == null || password == null) { return s; } Exception ex = null; 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("POST"); 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>", "\"\""); System.err.println("buf: " + buf.toString()); System.err.println("res: " + response); } JSONObject obj = parse(new ByteArrayInputStream(response.getBytes())); conn.disconnect(); access_token = obj.getString("access_token"); String expires = obj.getString("expires_in"); expires_timeout = now() + Long.parseLong(expires); return Status.OK; } } catch (MalformedURLException e) { ex = e; } catch (IOException e) { ex = e; } catch (JSONException e) { ex = e; } if (conn != null) conn.disconnect(); s.ex = ex; if (ex != null) { ex.printStackTrace(); } return s; }
From source file:com.dao.ShopThread.java
private HttpURLConnection getHttpPostConn(String url) throws Exception { LogUtil.debugPrintf("getHttpPostConn url===" + url); URL obj = new URL(url); HttpURLConnection conn; conn = (HttpURLConnection) obj.openConnection(); conn.setRequestMethod("POST"); if (null != this.cookies) { conn.addRequestProperty("Cookie", GenericUtil.cookieFormat(this.cookies)); }/*from ww w . ja v a 2 s . c o m*/ conn.setRequestProperty("Host", "consignment.5173.com"); 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("Content-Type", "application/x-www-form-urlencoded"); // conn.setRequestProperty("X-Requested-With", "XMLHttpRequest"); conn.setRequestProperty("Referer", url); conn.setRequestProperty("Connection", "keep-alive"); conn.setDoOutput(true); conn.setDoInput(true); return conn; }
From source file:org.runnerup.export.JoggSE.java
@Override public Status connect() { if (isConnected) { return Status.OK; }//from www . jav a 2s. c om Status s = Status.NEED_AUTH; s.authMethod = Uploader.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("POST"); 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); System.err.println("reply: " + e.getTextContent()); if (e != null && e.getTextContent() != null && LOGIN_OK.contentEquals(e.getTextContent())) { isConnected = true; return Uploader.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 = Uploader.Status.ERROR; s.ex = ex; if (ex != null) { ex.printStackTrace(); } return s; }
From source file:com.auto.solution.TestManager.TESTRAILTestManager.java
private Object sendRequest(String method, String uri, Object data) throws MalformedURLException, IOException, APIException { URL url = new URL(this.m_url + uri); // Create the connection object and set the required HTTP method // (GET/POST) and headers (content type and basic auth). HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.addRequestProperty("Content-Type", "application/json"); String auth = getAuthorization(this.m_user, this.m_password); conn.addRequestProperty("Authorization", "Basic " + auth); if (method == "POST") { // Add the POST arguments, if any. We just serialize the passed // data object (i.e. a dictionary) and then add it to the // request body. if (data != null) { byte[] block = JSONValue.toJSONString(data).getBytes("UTF-8"); conn.setDoOutput(true);//w w w. j av a 2 s . c o m OutputStream ostream = conn.getOutputStream(); ostream.write(block); ostream.flush(); } } // Execute the actual web request (if it wasn't already initiated // by getOutputStream above) and record any occurred errors (we use // the error stream in this case). int status = conn.getResponseCode(); InputStream istream; if (status != 200) { istream = conn.getErrorStream(); if (istream == null) { throw new APIException( "TestRail API return HTTP " + status + " (No additional error message received)"); } } else { istream = conn.getInputStream(); } // Read the response body, if any, and deserialize it from JSON. String text = ""; if (istream != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(istream, "UTF-8")); String line; while ((line = reader.readLine()) != null) { text += line; text += System.getProperty("line.separator"); } reader.close(); } Object result; if (text != "") { result = JSONValue.parse(text); } else { result = new JSONObject(); } // Check for any occurred errors and add additional details to // the exception message, if any (e.g. the error message returned // by TestRail). if (status != 200) { String error = "No additional error message received"; if (result != null && result instanceof JSONObject) { JSONObject obj = (JSONObject) result; if (obj.containsKey("error")) { error = '"' + (String) obj.get("error") + '"'; } } throw new APIException("TestRail API returned HTTP " + status + "(" + error + ")"); } return result; }