List of usage examples for java.net HttpURLConnection getOutputStream
public OutputStream getOutputStream() throws IOException
From source file:gribbit.util.RequestBuilder.java
/** * Make a GET or POST request, handling up to 6 redirects, and return the response. If isBinaryResponse is true, * returns a byte[] array, otherwise returns the response as a String. *///from w w w. ja v a2 s . c o m private static Object makeRequest(String url, String[] keyValuePairs, boolean isGET, boolean isBinaryResponse, int redirDepth) { if (redirDepth > 6) { throw new IllegalArgumentException("Too many redirects"); } HttpURLConnection connection = null; try { // Add the URL query params if this is a GET request String reqURL = isGET ? url + "?" + WebUtils.buildQueryString(keyValuePairs) : url; connection = (HttpURLConnection) new URL(reqURL).openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setInstanceFollowRedirects(false); connection.setRequestMethod(isGET ? "GET" : "POST"); connection.setUseCaches(false); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/43.0.2357.125 Safari/537.36"); if (!isGET) { // Send the body if this is a POST request connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("charset", "utf-8"); String params = WebUtils.buildQueryString(keyValuePairs); connection.setRequestProperty("Content-Length", Integer.toString(params.length())); try (DataOutputStream w = new DataOutputStream(connection.getOutputStream())) { w.writeBytes(params); w.flush(); } } if (connection.getResponseCode() == HttpResponseStatus.FOUND.code()) { // Follow a redirect. For safety, the params are not passed on, and the method is forced to GET. return makeRequest(connection.getHeaderField("Location"), /* keyValuePairs = */null, /* isGET = */ true, isBinaryResponse, redirDepth + 1); } else if (connection.getResponseCode() == HttpResponseStatus.OK.code()) { // For 200 OK, return the text of the response if (isBinaryResponse) { ByteArrayOutputStream output = new ByteArrayOutputStream(32768); IOUtils.copy(connection.getInputStream(), output); return output.toByteArray(); } else { StringWriter writer = new StringWriter(1024); IOUtils.copy(connection.getInputStream(), writer, "UTF-8"); return writer.toString(); } } else { throw new IllegalArgumentException( "Got non-OK HTTP response code: " + connection.getResponseCode()); } } catch (Exception e) { throw new IllegalArgumentException( "Exception during " + (isGET ? "GET" : "POST") + " request: " + e.getMessage(), e); } finally { if (connection != null) { try { connection.disconnect(); } catch (Exception e) { } } } }
From source file:com.ibm.stocator.fs.swift.auth.PasswordScopeAccessProvider.java
/** * Authentication logic/* w w w.j a v a 2 s. c o m*/ * * @return Access JOSS access object * @throws IOException if failed to parse the response */ public Access passwordScopeAuth() throws IOException { InputStreamReader reader = null; BufferedReader bufReader = null; try { JSONObject user = new JSONObject(); user.put("id", mUserId); user.put("password", mPassword); JSONObject password = new JSONObject(); password.put("user", user); JSONArray methods = new JSONArray(); methods.add("password"); JSONObject identity = new JSONObject(); identity.put("methods", methods); identity.put("password", password); JSONObject project = new JSONObject(); project.put("id", mProjectId); JSONObject scope = new JSONObject(); scope.put("project", project); JSONObject auth = new JSONObject(); auth.put("identity", identity); auth.put("scope", scope); JSONObject requestBody = new JSONObject(); requestBody.put("auth", auth); HttpURLConnection connection = (HttpURLConnection) new URL(mAuthUrl).openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Content-Type", "application/json"); OutputStream output = connection.getOutputStream(); output.write(requestBody.toString().getBytes()); int status = connection.getResponseCode(); if (status != 201) { return null; } reader = new InputStreamReader(connection.getInputStream()); bufReader = new BufferedReader(reader); String res = bufReader.readLine(); JSONParser parser = new JSONParser(); JSONObject jsonResponse = (JSONObject) parser.parse(res); String token = connection.getHeaderField("X-Subject-Token"); PasswordScopeAccess access = new PasswordScopeAccess(jsonResponse, token, mPrefferedRegion); bufReader.close(); reader.close(); connection.disconnect(); return access; } catch (Exception e) { if (bufReader != null) { bufReader.close(); } if (reader != null) { reader.close(); } throw new IOException(e); } }
From source file:com.orange.oidc.secproxy_service.HttpOpenidConnect.java
public static boolean logout(String server_url) { if (isEmpty(server_url)) { Logd(TAG, "revokSite no server url"); return false; }/*from w w w . j a v a 2 s .co m*/ if (!server_url.endsWith("/")) server_url += "/"; // get end session endpoint String end_session_endpoint = getEndpointFromConfigOidc("end_session_endpoint", server_url); if (isEmpty(end_session_endpoint)) { Logd(TAG, "logout : could not get end_session_endpoint on server : " + server_url); return false; } // set up connection HttpURLConnection huc = getHUC(end_session_endpoint); // TAZTAG test // huc.setInstanceFollowRedirects(false); huc.setInstanceFollowRedirects(true); // result : follows redirection is ok for taztag huc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); huc.setDoOutput(true); huc.setChunkedStreamingMode(0); // prepare parameters List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); try { // write parameters to http connection OutputStream os = huc.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); // get URL encoded string from list of key value pairs String postParam = getQuery(nameValuePairs); Logd("Logout", "url: " + end_session_endpoint); Logd("Logout", "POST: " + postParam); writer.write(postParam); writer.flush(); writer.close(); os.close(); // try to connect huc.connect(); // connexion status int responseCode = huc.getResponseCode(); Logd(TAG, "Logout response: " + responseCode); // if 200 - OK if (responseCode == 200) { return true; } huc.disconnect(); } catch (Exception e) { e.printStackTrace(); return false; } return false; }
From source file:net.terryyiu.emailservice.providers.AbstractEmailServiceProvider.java
@Override public boolean send(Email email) throws IOException { HttpURLConnection connection = createConnection(); // Create a Map from an email object, which can be translated to JSON which // the specific email service provider understands. Map<String, Object> map = getRequestPostData(email); ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(map); DataOutputStream dos = new DataOutputStream(connection.getOutputStream()); dos.writeBytes(json);//from w w w .j a va 2 s. c o m dos.flush(); dos.close(); int responseCode = connection.getResponseCode(); System.out.println("\nSending 'POST' request to URL : " + getServiceUrl()); System.out.println("JSON: " + json); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); connection.disconnect(); return false; }
From source file:com.cloudbees.mtslaves.client.RemoteReference.java
protected HttpURLConnection postJson(HttpURLConnection con, JSONObject json) throws IOException { try {/*from w w w. j av a2 s.c o m*/ token.authorizeRequest(con); con.setDoOutput(true); con.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); con.connect(); // send JSON OutputStreamWriter w = new OutputStreamWriter(con.getOutputStream(), "UTF-8"); json.write(w); w.close(); return con; } catch (IOException e) { throw (IOException) new IOException("Failed to POST to " + url).initCause(e); } }
From source file:crow.weibo.util.WeiboUtil.java
public static String multipartPost(HttpURLConnection conn, List<PostParameter> params) throws IOException { OutputStream os;// w w w.ja v a 2 s . c o m List<PostParameter> dataparams = new ArrayList<PostParameter>(); for (PostParameter key : params) { if (key.isFile()) { dataparams.add(key); } } String BOUNDARY = Util.md5(String.valueOf(System.currentTimeMillis())); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Charsert", "UTF-8"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY); ByteArrayBuffer buff = new ByteArrayBuffer(1000); for (PostParameter p : params) { byte[] arr = p.toMultipartByte(BOUNDARY, "UTF-8"); buff.append(arr, 0, arr.length); } String end = "--" + BOUNDARY + "--" + "\r\n"; byte[] endArr = end.getBytes(); buff.append(endArr, 0, endArr.length); conn.setRequestProperty("Content-Length", buff.length() + ""); conn.connect(); os = new BufferedOutputStream(conn.getOutputStream()); os.write(buff.toByteArray()); buff.clear(); os.flush(); String response = ""; response = Util.inputStreamToString(conn.getInputStream()); return response; }
From source file:blueprint.sdk.google.gcm.GcmSender.java
private GcmResponse send(String json) throws IOException { HttpURLConnection http = (HttpURLConnection) new URL(GCM_URL).openConnection(); http.setRequestMethod("POST"); http.addRequestProperty("Authorization", "key=" + apiKey); http.addRequestProperty("Content-Type", "application/json"); http.setDoOutput(true);/* w w w . jav a2s.co m*/ OutputStream os = http.getOutputStream(); os.write(json.getBytes()); os.close(); http.connect(); return decodeResponse(http); }
From source file:com.yahoo.druid.hadoop.DruidHelper.java
protected List<DataSegment> getSegmentsToLoad(String dataSource, Interval interval, String overlordUrl) { String urlStr = "http://" + overlordUrl + "/druid/indexer/v1/action"; logger.info("Sending request to overlord at " + urlStr); String requestJson = getSegmentListUsedActionJson(dataSource, interval.toString()); logger.info("request json is " + requestJson); int numTries = 3; //TODO: should be configurable? for (int trial = 0; trial < numTries; trial++) { try {//from w ww . j a v a 2s .c om logger.info("attempt number {} to get list of segments from overlord", trial); URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("content-type", "application/json"); conn.setUseCaches(false); conn.setDoOutput(true); conn.setConnectTimeout(60000); //TODO: 60 secs, shud be configurable? OutputStream out = conn.getOutputStream(); out.write(requestJson.getBytes()); out.close(); int responseCode = conn.getResponseCode(); if (responseCode == 200) { ObjectMapper mapper = DruidInitialization.getInstance().getObjectMapper(); Map<String, Object> obj = mapper.readValue(conn.getInputStream(), new TypeReference<Map<String, Object>>() { }); return mapper.convertValue(obj.get("result"), new TypeReference<List<DataSegment>>() { }); } else { logger.warn( "Attempt Failed to get list of segments from overlord. response code {} , response {}", responseCode, IOUtils.toString(conn.getInputStream())); } } catch (Exception ex) { logger.warn("Exception in getting list of segments from overlord", ex); } try { Thread.sleep(5000); //wait before next trial } catch (InterruptedException ex) { Throwables.propagate(ex); } } throw new RuntimeException( String.format("failed to find list of segments, dataSource[%s], interval[%s], overlord[%s]", dataSource, interval, overlordUrl)); }
From source file:org.yawlfoundation.yawl.engine.interfce.Interface_Client.java
/** * Submits data on a HTTP connection//from w w w . j a v a 2s . c om * @param connection a valid, open HTTP connection * @param data the data to submit * @throws IOException when there's some kind of communication problem */ private void sendData(HttpURLConnection connection, String data) throws IOException { OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); out.write(data); out.close(); }
From source file:ai.api.RequestTask.java
@Override protected String doInBackground(final String... params) { final String payload = params[0]; if (TextUtils.isEmpty(payload)) { throw new IllegalArgumentException("payload argument should not be empty"); }//from w w w. j a v a 2 s. c o m String response = null; HttpURLConnection connection = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.connect(); final BufferedOutputStream outputStream = new BufferedOutputStream(connection.getOutputStream()); IOUtils.write(payload, outputStream, Charsets.UTF_8); outputStream.close(); final InputStream inputStream = new BufferedInputStream(connection.getInputStream()); response = IOUtils.toString(inputStream, Charsets.UTF_8); inputStream.close(); return response; } catch (final IOException e) { Log.e(TAG, "Can't make request to the Speaktoit AI service. Please, check connection settings and API access token.", e); } finally { if (connection != null) { connection.disconnect(); } } return null; }