List of usage examples for java.net HttpURLConnection getOutputStream
public OutputStream getOutputStream() throws IOException
From source file:fi.hip.sicx.store.HIPStoreClient.java
private void closeConnection(HttpURLConnection conn) { readInput(conn);//from w w w. j av a2 s .c o m try { conn.getInputStream().close(); conn.getOutputStream().close(); } catch (Exception ex) { } }
From source file:alluxio.rest.TestCase.java
/** * Runs the test case and returns the output. *///from w w w.j a va 2s.c o m public String call() throws Exception { HttpURLConnection connection = (HttpURLConnection) createURL().openConnection(); connection.setRequestMethod(mMethod); if (mOptions.getInputStream() != null) { connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/octet-stream"); ByteStreams.copy(mOptions.getInputStream(), connection.getOutputStream()); } if (mOptions.getBody() != null) { connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/json"); ObjectMapper mapper = new ObjectMapper(); // make sure that serialization of empty objects does not fail mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); OutputStream os = connection.getOutputStream(); os.write(mapper.writeValueAsString(mOptions.getBody()).getBytes()); os.close(); } connection.connect(); if (connection.getResponseCode() != Response.Status.OK.getStatusCode()) { InputStream errorStream = connection.getErrorStream(); if (errorStream != null) { Assert.fail("Request failed: " + IOUtils.toString(errorStream)); } Assert.fail("Request failed with status code " + connection.getResponseCode()); } return getResponse(connection); }
From source file:com.contrastsecurity.ide.eclipse.core.extended.ExtendedContrastSDK.java
private HttpURLConnection makeConnection(String url, String method, Object body) throws IOException { HttpURLConnection connection = makeConnection(url, method); connection.setDoOutput(true);/*from ww w.j a va2 s . c o m*/ connection.setRequestProperty("Content-Type", "application/json"); OutputStream os = connection.getOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8"); osw.write(gson.toJson(body)); osw.flush(); osw.close(); os.close(); return connection; }
From source file:alluxio.worker.block.BlockWorkerClientRestApiTest.java
@Test public void writeBlock() throws Exception { Map<String, String> params = new HashMap<>(); params.put("blockId", Long.toString(BLOCK_ID)); params.put("sessionId", Long.toString(SESSION_ID)); params.put("offset", "0"); params.put("length", Long.toString(INITIAL_BYTES)); TestCase testCase = new TestCase(mHostname, mPort, getEndpoint(BlockWorkerClientRestServiceHandler.WRITE_BLOCK), params, HttpMethod.POST, null); HttpURLConnection connection = (HttpURLConnection) testCase.createURL().openConnection(); connection.setRequestProperty("Content-Type", MediaType.APPLICATION_OCTET_STREAM); connection.setRequestMethod(testCase.getMethod()); connection.setDoOutput(true);/*from w ww . j a v a 2 s . c om*/ connection.connect(); connection.getOutputStream().write(BYTE_BUFFER.array()); Assert.assertEquals(testCase.getEndpoint(), Response.Status.OK.getStatusCode(), connection.getResponseCode()); Assert.assertEquals("", testCase.getResponse(connection)); // Verify that the right data was written. mBlockWorker.commitBlock(SESSION_ID, BLOCK_ID); long lockId = mBlockWorker.lockBlock(SESSION_ID, BLOCK_ID); String file = mBlockWorker.readBlock(SESSION_ID, BLOCK_ID, lockId); byte[] result = new byte[INITIAL_BYTES]; IOUtils.readFully(new FileInputStream(file), result); Assert.assertArrayEquals(BYTE_BUFFER.array(), result); }
From source file:com.tonchidot.nfc_contact_exchanger.lib.PictureUploader.java
private String doFileUploadJson(String url, String fileParamName, byte[] data) { try {//from w ww . jav a 2s .co m String boundary = "BOUNDARY" + new Date().getTime() + "BOUNDARY"; String lineEnd = "\r\n"; String twoHyphens = "--"; URL connUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) connUrl.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"" + fileParamName + "\";filename=\"photo.jpg\"" + lineEnd); dos.writeBytes(lineEnd); dos.write(data, 0, data.length); dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); dos.flush(); dos.close(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder result = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { result.append(line); } rd.close(); return result.toString(); } catch (IOException e) { if (Config.LOGD) { Log.d(TAG, "IOException : " + e); } } return null; }
From source file:net.sf.okapi.filters.drupal.DrupalConnector.java
/** * Log in to start session/*from w w w . j av a2 s . c o m*/ * @param username * @param password * @return * @throws IOException * @throws ParseException */ @SuppressWarnings("unchecked") boolean login() { try { URL url = new URL(host + "rest/user/login"); HttpURLConnection conn = createConnection(url, "POST", true); JSONObject login = new JSONObject(); login.put("username", user); login.put("password", pass); OutputStream os = conn.getOutputStream(); os.write(login.toJSONString().getBytes()); os.flush(); if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { conn.disconnect(); return false; } BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); JSONParser parser = new JSONParser(); JSONObject obj = (JSONObject) parser.parse(reader); session_cookie = obj.get("session_name") + "=" + obj.get("sessid"); conn.disconnect(); } catch (Throwable e) { throw new OkapiIOException("Error in login().", e); } return true; }
From source file:org.freshrss.easyrss.network.NetworkClient.java
public InputStream doPostStream(final String url, final String params) throws IOException, NetworkException { final HttpURLConnection conn = makeConnection(url); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); if (auth != null) { conn.setRequestProperty("Authorization", "GoogleLogin auth=" + auth); }// www . j a v a2 s .c o m conn.setDoInput(true); conn.setDoOutput(true); final OutputStream output = conn.getOutputStream(); output.write(params.getBytes()); output.flush(); output.close(); conn.connect(); try { final int resStatus = conn.getResponseCode(); if (resStatus == HttpStatus.SC_UNAUTHORIZED) { ReaderAccountMgr.getInstance().invalidateAuth(); } if (resStatus != HttpStatus.SC_OK) { throw new NetworkException("Invalid HTTP status " + resStatus + ": " + url + "."); } } catch (final IOException exception) { if (exception.getMessage() != null && exception.getMessage().contains("authentication")) { ReaderAccountMgr.getInstance().invalidateAuth(); } throw exception; } return conn.getInputStream(); }
From source file:com.geozen.demo.foursquare.jiramot.Util.java
/** * Connect to an HTTP URL and return the response as a string. * /*from w ww. java2 s . c om*/ * Note that the HTTP method override is used on non-GET requests. (i.e. * requests are made as "POST" with method specified in the body). * * @param url * - the resource to open: must be a welformed URL * @param method * - the HTTP method to use ("GET", "POST", etc.) * @param params * - the query parameter for the URL (e.g. access_token=foo) * @return the URL contents as a String * @throws MalformedURLException * - if the URL format is invalid * @throws IOException * - if a network problem occurs */ public static String openUrl(String url, String method, Bundle params) throws MalformedURLException, IOException { // random string as boundary for multi-part http post String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f"; String endLine = "\r\n"; OutputStream os; if (method.equals("GET")) { url = url + "?" + encodeUrl(params); } Log.d("Foursquare-Util", method + " URL: " + url); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " GeoZen"); if (!method.equals("GET")) { Bundle dataparams = new Bundle(); for (String key : params.keySet()) { if (params.getByteArray(key) != null) { dataparams.putByteArray(key, params.getByteArray(key)); } } // use method override if (!params.containsKey("method")) { params.putString("method", method); } if (params.containsKey("access_token")) { String decoded_token = URLDecoder.decode(params.getString("access_token")); params.putString("access_token", decoded_token); } conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Connection", "Keep-Alive"); conn.connect(); os = new BufferedOutputStream(conn.getOutputStream()); os.write(("--" + strBoundary + endLine).getBytes()); os.write((encodePostBody(params, strBoundary)).getBytes()); os.write((endLine + "--" + strBoundary + endLine).getBytes()); if (!dataparams.isEmpty()) { for (String key : dataparams.keySet()) { os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes()); os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes()); os.write(dataparams.getByteArray(key)); os.write((endLine + "--" + strBoundary + endLine).getBytes()); } } os.flush(); } String response = ""; try { response = read(conn.getInputStream()); } catch (FileNotFoundException e) { // Error Stream contains JSON that we can parse to a FB error response = read(conn.getErrorStream()); } return response; }
From source file:hudson.model.SlaveTest.java
private void post(String url, String xml) throws Exception { HttpURLConnection con = (HttpURLConnection) new URL(j.getURL(), url).openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/xml;charset=UTF-8"); con.setRequestProperty(CrumbIssuer.DEFAULT_CRUMB_NAME, "test"); con.setDoOutput(true);/* w ww . j a v a 2s . c om*/ con.getOutputStream().write(xml.getBytes("UTF-8")); con.getOutputStream().close(); IOUtils.copy(con.getInputStream(), System.out); }
From source file:com.parasoft.em.client.impl.JSONClient.java
protected JSONObject doPost(String restPath, JSONObject payload) throws IOException { HttpURLConnection connection = getConnection(restPath); connection.setRequestMethod("POST"); if (payload != null) { String payloadString = payload.toString(); connection.setRequestProperty("Content-Type", "application/json; charset=utf-8"); BufferedOutputStream stream = new BufferedOutputStream(connection.getOutputStream()); try {//from w w w . java 2 s . c o m byte[] bytes = payloadString.getBytes("UTF-8"); stream.write(bytes, 0, bytes.length); } finally { stream.close(); } } int responseCode = connection.getResponseCode(); if (responseCode / 100 == 2) { return getResponseJSON(connection.getInputStream()); } else { String errorMessage = getResponseString(connection.getErrorStream()); throw new IOException(restPath + ' ' + responseCode + '\n' + errorMessage); } }