List of usage examples for java.net HttpURLConnection addRequestProperty
public void addRequestProperty(String key, String value)
From source file:com.exzogeni.dk.http.HttpTask.java
private void onPrepareConnectionInternal(HttpURLConnection cn) throws Exception { final URI uri = cn.getURL().toURI(); cn.setRequestMethod(getMethodName()); cn.setConnectTimeout(mTimeoutMs);/*from w w w .j av a 2 s. c o m*/ cn.setReadTimeout(mTimeoutMs); final CookieManager cm = mHttpManager.getCookieManager(); final Map<String, List<String>> cookies = cm.get(uri, new HashMap<String, List<String>>()); for (final Map.Entry<String, List<String>> cookie : cookies.entrySet()) { for (final String value : cookie.getValue()) { cn.addRequestProperty(cookie.getKey(), value); } } for (final Map.Entry<String, List<String>> header : mHeaders.entrySet()) { for (final String value : header.getValue()) { cn.addRequestProperty(header.getKey(), value); } } onPrepareConnection(cn); }
From source file:org.runnerup.export.GooglePlus.java
public Status refreshToken() { Status s = Status.OK;//from www. j a v a2 s . c om 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("POST"); conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); postData(conn, fv); InputStream in = new BufferedInputStream(conn.getInputStream()); JSONObject obj = 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.runnerup.export.MapMyRunSynchronizer.java
@Override public Status connect() { if (isConfigured()) { return Status.OK; }//from w ww. j av 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 { String pass = md5pass; if (pass == null) { pass = toHexString(Encryption.md5(password)); } /** * get user id/key */ conn = (HttpURLConnection) new URL(GET_USER_URL).openConnection(); conn.setDoOutput(true); conn.setRequestMethod(RequestMethod.POST.name()); conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); FormValues kv = new FormValues(); kv.put("consumer_key", CONSUMER_KEY); kv.put("u", username); kv.put("p", pass); { OutputStream wr = new BufferedOutputStream(conn.getOutputStream()); kv.write(wr); wr.flush(); wr.close(); InputStream in = new BufferedInputStream(conn.getInputStream()); JSONObject obj = SyncHelper.parse(in); conn.disconnect(); try { JSONObject user = obj.getJSONObject("result").getJSONObject("output").getJSONObject("user"); user_id = user.getString("user_id"); user_key = user.getString("user_key"); md5pass = pass; return Synchronizer.Status.OK; } catch (JSONException e) { Log.e(getName(), "obj: " + obj); throw e; } } } catch (MalformedURLException e) { ex = e; } catch (IOException e) { ex = e; } catch (JSONException e) { ex = e; } catch (NoSuchAlgorithmException e) { ex = e; } if (conn != null) conn.disconnect(); s.ex = ex; if (ex != null) { ex.printStackTrace(); } return s; }
From source file:org.wso2.msf4j.internal.router.HttpServerTest.java
@Test public void testListHeaderParam() throws IOException { List<String> names = ImmutableList.of("name1", "name3", "name2", "name1"); HttpURLConnection urlConn = request("/test/v1/listHeaderParam", HttpMethod.GET); for (String name : names) { urlConn.addRequestProperty("name", name); }//from w w w.j a v a 2 s.c om Assert.assertEquals(200, urlConn.getResponseCode()); Assert.assertEquals(Joiner.on(',').join(names), getContent(urlConn)); urlConn.disconnect(); }
From source file:org.runnerup.export.MapMyRunSynchronizer.java
@Override public Status upload(SQLiteDatabase db, long mID) { Status s;/* w w w. ja v a 2 s . c o m*/ if ((s = connect()) != Status.OK) { return s; } TCX tcx = new TCX(db); HttpURLConnection conn = null; Exception ex = null; try { StringWriter writer = new StringWriter(); Pair<String, Sport> res = tcx.exportWithSport(mID, writer); Sport sport = res.second; conn = (HttpURLConnection) new URL(IMPORT_URL).openConnection(); conn.setDoOutput(true); conn.setRequestMethod(RequestMethod.POST.name()); conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); FormValues kv = new FormValues(); kv.put("consumer_key", CONSUMER_KEY); kv.put("u", username); kv.put("p", md5pass); kv.put("o", "json"); kv.put("baretcx", "1"); kv.put("tcx", writer.toString()); { OutputStream wr = new BufferedOutputStream(conn.getOutputStream()); kv.write(wr); wr.flush(); wr.close(); InputStream in = new BufferedInputStream(conn.getInputStream()); JSONObject obj = SyncHelper.parse(in); conn.disconnect(); Log.e(getName(), obj.toString()); JSONObject result = obj.getJSONObject("result").getJSONObject("output").getJSONObject("result"); final String workout_id = result.getString("workout_id"); final String workout_key = result.getString("workout_key"); final JSONObject workout = result.getJSONObject("workout"); final String raw_workout_date = workout.getString("raw_workout_date"); String workout_type_id = workout.getString("workout_type_id"); if (sport != null && sport2mapmyrunMap.containsKey(sport)) workout_type_id = sport2mapmyrunMap.get(sport).toString(); kv.clear(); kv.put("consumer_key", CONSUMER_KEY); kv.put("u", username); kv.put("p", md5pass); kv.put("o", "json"); kv.put("workout_id", workout_id); kv.put("workout_key", workout_key); kv.put("workout_type_id", workout_type_id); kv.put("workout_description", "RunnerUp - " + raw_workout_date); kv.put("notes", tcx.getNotes()); kv.put("privacy_setting", "1"); // friends conn = (HttpURLConnection) new URL(UPDATE_URL).openConnection(); conn.setDoOutput(true); conn.setRequestMethod(RequestMethod.POST.name()); conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); wr = new BufferedOutputStream(conn.getOutputStream()); kv.write(wr); wr.flush(); wr.close(); in = new BufferedInputStream(conn.getInputStream()); obj = SyncHelper.parse(in); conn.disconnect(); s = Status.OK; s.activityId = mID; return s; } } catch (IOException e) { ex = e; } catch (JSONException e) { ex = e; } s = Synchronizer.Status.ERROR; s.ex = ex; s.activityId = mID; if (ex != null) { ex.printStackTrace(); } return s; }
From source file:com.checkmarx.jenkins.CxWebService.java
private CxWSResponseRunID sendScanRequest(final FilePath base64ZipFile, String soapActionName, Pair<byte[], byte[]> soapMessage, XmlResponseParser xmlResponseParser) throws AbortException { try {/*from w w w. j a va 2 s . c o m*/ // Create HTTP connection final HttpURLConnection streamingUrlConnection = (HttpURLConnection) webServiceUrl.openConnection(); streamingUrlConnection.addRequestProperty("Content-Type", "text/xml; charset=utf-8"); streamingUrlConnection.addRequestProperty("SOAPAction", String.format("\"http://Checkmarx.com/v7/%s\"", soapActionName)); streamingUrlConnection.setDoOutput(true); // Calculate the length of the soap message final long length = soapMessage.getLeft().length + soapMessage.getRight().length + base64ZipFile.length(); streamingUrlConnection.setFixedLengthStreamingMode((int) length); streamingUrlConnection.connect(); final OutputStream os = streamingUrlConnection.getOutputStream(); logger.info("Uploading sources to Checkmarx server"); os.write(soapMessage.getLeft()); final InputStream fis = base64ZipFile.read(); org.apache.commons.io.IOUtils.copyLarge(fis, os); os.write(soapMessage.getRight()); os.close(); fis.close(); logger.info("Finished uploading sources to Checkmarx server"); CxWSResponseRunID cxWSResponseRunID = xmlResponseParser.parse(streamingUrlConnection.getInputStream()); if (!cxWSResponseRunID.isIsSuccesfull()) { String message = "Submission of sources for scan failed: \n" + cxWSResponseRunID.getErrorMessage(); throw new AbortException(message); } return cxWSResponseRunID; } catch (HttpRetryException e) { String consoleMessage = "\nCheckmarx plugin for Jenkins does not support Single sign-on authentication." + "\nPlease, configure Checkmarx server to work in Anonymous authentication mode.\n"; logger.error(consoleMessage); throw new AbortException(e.getMessage()); } catch (IOException | JAXBException | XMLStreamException | InterruptedException e) { logger.error(e.getMessage(), e); throw new AbortException(e.getMessage()); } }
From source file:com.machinelinking.api.client.APIClient.java
private InputStream sendRequest(String service, String group, Map<String, Object> properties) throws IOException { try {// ww w .j av a 2s.c om URL url = new URL(service); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setConnectTimeout(connTimeout); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setDoOutput(true); properties.put(ParamsValidator.app_id, appId); properties.put(ParamsValidator.app_key, appKey); StringBuilder data = ParamsValidator.getInstance().buildRequest(group, properties); httpURLConnection.addRequestProperty("Content-type", "application/x-www-form-urlencoded; charset=UTF-8"); DataOutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream()); dataOutputStream.write(data.toString().getBytes()); dataOutputStream.close(); if (httpURLConnection.getResponseCode() == 200) { return httpURLConnection.getInputStream(); } else { return httpURLConnection.getErrorStream(); } } catch (MalformedURLException e) { throw new IllegalStateException(e); } }
From source file:com.elevenpaths.googleindexretriever.GoogleSearch.java
public void getCaptcha(String image) { try {//from w ww .jav a 2s. com URL obj = new URL(image); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // optional default is GET con.setRequestMethod("GET"); // add request header con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0"); con.addRequestProperty("Connection", "keep-alive"); con.getResponseCode(); tokenCookie = con.getHeaderField("Set-Cookie"); // creating the input stream from google image BufferedInputStream in = new BufferedInputStream(con.getInputStream()); // my local file writer, output stream BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("Captcha.png")); // until the end of data, keep saving into file. int i; while ((i = in.read()) != -1) { out.write(i); } out.flush(); in.close(); out.close(); con.disconnect(); } catch (MalformedURLException e) { } catch (IOException e) { // TODO: handle exception } }
From source file:co.cask.cdap.gateway.handlers.StreamHandlerTest.java
@Test public void testSimpleStreamEnqueue() throws Exception { // Create new stream. HttpURLConnection urlConn = openURL(createURL("streams/test_stream_enqueue"), HttpMethod.PUT); Assert.assertEquals(HttpResponseStatus.OK.getCode(), urlConn.getResponseCode()); urlConn.disconnect();/*from w w w . j av a 2s. c o m*/ // Enqueue 10 entries for (int i = 0; i < 10; ++i) { urlConn = openURL(createURL("streams/test_stream_enqueue"), HttpMethod.POST); urlConn.setDoOutput(true); urlConn.addRequestProperty("test_stream_enqueue.header1", Integer.toString(i)); urlConn.getOutputStream().write(Integer.toString(i).getBytes(Charsets.UTF_8)); Assert.assertEquals(HttpResponseStatus.OK.getCode(), urlConn.getResponseCode()); urlConn.disconnect(); } // Fetch 10 entries urlConn = openURL(createURL("streams/test_stream_enqueue/events?limit=10"), HttpMethod.GET); List<StreamEvent> events = GSON.fromJson( new String(ByteStreams.toByteArray(urlConn.getInputStream()), Charsets.UTF_8), new TypeToken<List<StreamEvent>>() { }.getType()); for (int i = 0; i < 10; i++) { StreamEvent event = events.get(i); int actual = Integer.parseInt(Charsets.UTF_8.decode(event.getBody()).toString()); Assert.assertEquals(i, actual); Assert.assertEquals(Integer.toString(i), event.getHeaders().get("header1")); } urlConn.disconnect(); }
From source file:org.runnerup.export.RunKeeperSynchronizer.java
JSONObject requestFeed(long from) throws IOException, JSONException { URL newurl = new URL(FEED_URL); HttpURLConnection conn = (HttpURLConnection) newurl.openConnection(); conn.setDoOutput(true);// ww w . j a v a2 s. com conn.setRequestMethod(RequestMethod.POST.name()); conn.addRequestProperty("Authorization", "Bearer " + feed_access_token); FormValues kv = new FormValues(); kv.put("lastPostTime", Long.toString(from)); kv.put("feedItemTypes", FEED_ITEM_TYPES); { OutputStream wr = new BufferedOutputStream(conn.getOutputStream()); kv.write(wr); wr.flush(); wr.close(); } int responseCode = conn.getResponseCode(); String amsg = conn.getResponseMessage(); InputStream in = new BufferedInputStream(conn.getInputStream()); JSONObject obj = SyncHelper.parse(in); conn.disconnect(); if (responseCode == HttpStatus.SC_OK) { return obj; } throw new IOException(amsg); }