Example usage for java.net HttpURLConnection getOutputStream

List of usage examples for java.net HttpURLConnection getOutputStream

Introduction

In this page you can find the example usage for java.net HttpURLConnection getOutputStream.

Prototype

public OutputStream getOutputStream() throws IOException 

Source Link

Document

Returns an output stream that writes to this connection.

Usage

From source file:de.fahrgemeinschaft.FahrgemeinschaftConnector.java

@Override
public String authenticate(String credential) throws Exception {
    System.out.println("refreshing authtoken");
    HttpURLConnection post = (HttpURLConnection) new URL(endpoint + SESSION).openConnection();
    post.setRequestProperty("User-Agent", USER_AGENT);
    post.setRequestProperty(APIKEY, Secret.APIKEY);
    post.setDoOutput(true);/*from   w  ww . j a  v a2s  .  c o  m*/
    post.getOutputStream()
            .write(new JSONObject().put(EMAIL, get(LOGIN)).put(PASSWD, credential).toString().getBytes());
    post.getOutputStream().close();
    JSONObject json = loadJson(post);
    if (post.getResponseCode() == 403)
        throw new AuthException();
    JSONObject auth = json.getJSONObject(AUTH);
    set(USER, auth.getString(ID_USER));
    JSONArray kvp = json.getJSONObject(USER).getJSONArray(KEY_VALUE_PAIRS);
    for (int i = 1; i < kvp.length(); i++) {
        String key = kvp.getJSONObject(i).getString(KEY);
        if (key.equals(FIRSTNAME))
            set(FIRSTNAME, kvp.getJSONObject(i).getString(VALUE));
        else if (key.equals(LASTNAME))
            set(LASTNAME, kvp.getJSONObject(i).getString(VALUE));
    }
    return auth.getString(AUTH_KEY);
}

From source file:com.yahoo.sql4d.sql4ddriver.DDataSource.java

/**
 * For firing simple queries(i.e non join queries).
 * @param jsonQuery/*w  ww  .ja  v  a 2  s  .  c om*/
 * @param print
 * @return 
 */
private Either<String, Either<Mapper4All, JSONArray>> fireQuery(String jsonQuery, boolean requiresMapping) {
    StringBuilder buff = new StringBuilder();
    try {
        URL url = null;
        try {
            url = new URL(String.format(brokerUrl, brokerHost, brokerPort));
        } catch (MalformedURLException ex) {
            Logger.getLogger(DDataSource.class.getName()).log(Level.SEVERE, null, ex);
            return new Left<>("Bad Url : " + ex);
        }
        Proxy proxy = Proxy.NO_PROXY;
        if (proxyHost != null) {
            proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
        }
        HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection(proxy);
        httpConnection.setRequestMethod("POST");
        httpConnection.addRequestProperty("content-type", "application/json");
        httpConnection.setDoOutput(true);
        httpConnection.getOutputStream().write(jsonQuery.getBytes());
        if (httpConnection.getResponseCode() == 500 || httpConnection.getResponseCode() == 404) {
            return new Left<>(String.format("Http %d : %s \n", httpConnection.getResponseCode(),
                    httpConnection.getResponseMessage()));
        }
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
        String line = null;
        while ((line = stdInput.readLine()) != null) {
            buff.append(line);
        }
    } catch (IOException ex) {
        Logger.getLogger(DDataSource.class.getName()).log(Level.SEVERE, null, ex);
    }
    JSONArray possibleResArray = null;
    try {
        possibleResArray = new JSONArray(buff.toString());
    } catch (JSONException je) {
        return new Left<>(String.format("Recieved data %s not in json format. \n", buff.toString()));
    }
    if (requiresMapping) {
        return new Right<String, Either<Mapper4All, JSONArray>>(
                new Left<Mapper4All, JSONArray>(new Mapper4All(possibleResArray)));
    }
    return new Right<String, Either<Mapper4All, JSONArray>>(new Right<Mapper4All, JSONArray>(possibleResArray));
}

From source file:net.maxgigapop.mrs.driver.GenericRESTDriver.java

private String executeHttpMethod(URL url, HttpURLConnection conn, String method, String body)
        throws IOException {
    conn.setRequestMethod(method);//from w  w  w  .ja  v a2 s. c  om
    conn.setRequestProperty("Content-type", "application/json");
    conn.setRequestProperty("Accept", "application/json");
    if (body != null && !body.isEmpty()) {
        conn.setDoOutput(true);
        try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
            wr.writeBytes(body);
            wr.flush();
        }
    }
    logger.log(Level.INFO, "Sending {0} request to URL : {1}", new Object[] { method, url });
    int responseCode = conn.getResponseCode();
    logger.log(Level.INFO, "Response Code : {0}", responseCode);

    StringBuilder responseStr;
    try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
        String inputLine;
        responseStr = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            responseStr.append(inputLine);
        }
    }
    return responseStr.toString();
}

From source file:com.helpmobile.rest.RestAccess.java

public String doGetRequest(String request, Map<String, Object> data, String method)
        throws MalformedURLException, IOException {

    StringBuilder postData = new StringBuilder();
    for (Map.Entry<String, Object> param : data.entrySet()) {
        if (postData.length() != 0) {
            postData.append('&');
        }//from   w  w w.j  a v  a 2  s . c o m
        postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
        postData.append('=');
        postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
    }
    URL path;
    path = new URL(ADDRESS + request + "?" + postData.toString());

    HttpURLConnection conn = (HttpURLConnection) path.openConnection();
    conn.setRequestMethod(method);
    conn.setRequestProperty("Content-Type", "application/json");

    conn.setRequestProperty("AppKey", KEY);
    conn.setUseCaches(false);
    conn.setDoInput(true);

    conn.setRequestProperty("Content-Length", "0");
    conn.setDoOutput(true);
    OutputStream output = conn.getOutputStream();
    output.flush();

    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
    conn.disconnect();
    //print result
    return response.toString();
}

From source file:com.commsen.jwebthumb.WebThumbService.java

/**
 * Helper method used to actually send {@link WebThumb} request and check for common errors.
 * /*from w  w w  .  ja va2s  . c om*/
 * @param webThumb the request to send
 * @return connection to extract the response from
 * @throws WebThumbException if any error occurs
 */
private HttpURLConnection sendWebThumb(WebThumb webThumb) throws WebThumbException {
    try {
        HttpURLConnection connection = (HttpURLConnection) new URL(WEB_THUMB_URL).openConnection();
        connection.setInstanceFollowRedirects(false);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");

        SimpleXmlSerializer.generateRequest(webThumb, connection.getOutputStream());

        int responseCode = connection.getResponseCode();
        String contentType = getContentType(connection);
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.fine("Request sent! Got response: " + responseCode + " " + connection.getResponseMessage());
            LOGGER.fine("Response content type: " + contentType);
            LOGGER.fine("Response content encoding: " + connection.getContentEncoding());
            LOGGER.fine("Response content length: " + connection.getContentLength());
        }

        if (responseCode == HttpURLConnection.HTTP_OK) {
            if (CONTENT_TYPE_TEXT_PLAIN.equals(contentType)) {
                throw new WebThumbException(
                        "Server side error: " + IOUtils.toString(connection.getInputStream()));
            }
            if (!CONTENT_TYPE_TEXT_XML.equals(contentType)) {
                throw new WebThumbException("Unknown content type in response: " + contentType);
            }
            return connection;
        } else {
            throw new WebThumbException("Server side error: " + connection.getResponseCode() + ") "
                    + connection.getResponseMessage());
        }
    } catch (MalformedURLException e) {
        throw new WebThumbException("failed to send request", e);
    } catch (IOException e) {
        throw new WebThumbException("failed to send request", e);
    }
}

From source file:org.jboss.aerogear.android.impl.http.HttpRestProviderTest.java

@Test
public void testPost() throws Exception {

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream(RESPONSE_DATA.length);
    HttpURLConnection connection = mock(HttpURLConnection.class);
    HttpRestProvider provider = new HttpRestProvider(SIMPLE_URL);
    setPrivateField(provider, "connectionPreparer", new HttpUrlConnectionProvider(connection));

    doReturn(HttpStatus.SC_OK).when(connection).getResponseCode();
    when(connection.getInputStream()).thenReturn(new ByteArrayInputStream(RESPONSE_DATA));
    when(connection.getOutputStream()).thenReturn(outputStream);
    when(connection.getHeaderFields()).thenReturn(RESPONSE_HEADERS);
    doCallRealMethod().when(connection).setRequestMethod(anyString());
    when(connection.getRequestMethod()).thenCallRealMethod();

    HeaderAndBody result = provider.post(REQUEST_DATA);
    assertEquals("POST", connection.getRequestMethod());
    assertArrayEquals(RESPONSE_DATA, result.getBody());
    assertNotNull(result.getHeader(HEADER_KEY1_NAME));
    assertNotNull(result.getHeader(HEADER_KEY2_NAME));
    assertEquals(HEADER_VALUE, result.getHeader(HEADER_KEY2_NAME));
    assertArrayEquals(RESPONSE_DATA, outputStream.toByteArray());

}

From source file:com.ibuildapp.romanblack.CataloguePlugin.utils.Utils.java

/**
 * Likes video with given position.//from w w  w. j ava  2 s . c om
 */
public static boolean like(final String innerurl) {
    try {
        String url = "https://graph.facebook.com/me/og.likes";

        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestProperty("Accept-Encoding", "identity");
        conn.setRequestProperty("charset", "utf-8");
        conn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (iPhone; U; " + "CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 "
                        + "(KHTML, like Gecko) Version/4.0.5 Mobile/8A293 " + "Safari/6531.22.7");

        conn.setRequestMethod("POST");
        conn.setDoOutput(true);

        StringBuilder sb = new StringBuilder();
        sb.append("method=");
        sb.append("POST");
        sb.append("&");
        sb.append("access_token=");
        sb.append(Authorization.getAuthorizedUser(Authorization.AUTHORIZATION_TYPE_FACEBOOK).getAccessToken());
        sb.append("&");
        sb.append("object=");
        sb.append(URLEncoder.encode(innerurl));

        String params = sb.toString();

        conn.getOutputStream().write(params.getBytes("UTF-8"));

        String response = "";
        try {
            InputStream in = conn.getInputStream();

            StringBuilder sbr = new StringBuilder();
            BufferedReader r = new BufferedReader(new InputStreamReader(in), 1000);
            for (String line = r.readLine(); line != null; line = r.readLine()) {
                sbr.append(line);
            }
            in.close();

            response = sbr.toString();
        } catch (FileNotFoundException e) {
            InputStream in = conn.getErrorStream();

            StringBuilder sbr = new StringBuilder();
            BufferedReader r = new BufferedReader(new InputStreamReader(in), 1000);
            for (String line = r.readLine(); line != null; line = r.readLine()) {
                sbr.append(line);
            }
            in.close();

            response = sbr.toString();
            Log.e(TAG, "response = " + response);
        }

        try {
            JSONObject obj = new JSONObject(response);
            obj.getString("id");
            return true;

        } catch (JSONException jSONEx) {
            //    fb       
            //                      // ?   ?  ?  ?   ?
            conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setRequestProperty("Accept-Encoding", "identity");
            conn.setRequestProperty("charset", "utf-8");
            conn.setRequestProperty("User-Agent",
                    "Mozilla/5.0 (iPhone; U; " + "CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 "
                            + "(KHTML, like Gecko) Version/4.0.5 Mobile/8A293 " + "Safari/6531.22.7");

            conn.setRequestMethod("POST");
            conn.setDoOutput(true);

            sb = new StringBuilder();
            sb.append("method=");
            sb.append("POST");
            sb.append("&");
            sb.append("access_token=");
            sb.append(Authorization.getAuthorizedUser(Authorization.AUTHORIZATION_TYPE_FACEBOOK)
                    .getAccessToken());
            sb.append("&");
            sb.append("object=");
            sb.append(URLEncoder.encode(innerurl));

            params = sb.toString();

            conn.getOutputStream().write(params.getBytes("UTF-8"));

            try {
                InputStream in = conn.getInputStream();

                StringBuilder sbr = new StringBuilder();
                BufferedReader r = new BufferedReader(new InputStreamReader(in), 1000);
                for (String line = r.readLine(); line != null; line = r.readLine()) {
                    sbr.append(line);
                }
                in.close();

                response = sbr.toString();
                Log.e(TAG, "response2 = " + response);

                try {
                    JSONObject obj = new JSONObject(response);
                    obj.getString("id");
                    return true;
                } catch (JSONException e) {
                    return false;
                }
            } catch (FileNotFoundException e) {
                return false;
            }
        }
    } catch (MalformedURLException mURLEx) {
        Log.d("", "");
        return false;
    } catch (IOException iOEx) {
        Log.d("", "");
        return false;
    } catch (Exception ex) {
        Log.d("", "");
        return false;
    }
}

From source file:org.callimachusproject.test.WebResource.java

public void put(String type, byte[] body) throws IOException {
    HttpURLConnection con = (HttpURLConnection) new URL(uri).openConnection();
    con.setRequestMethod("PUT");
    con.setRequestProperty("If-Match", "*");
    con.setRequestProperty("Content-Type", type);
    con.setDoOutput(true);// w  w w.j  a va  2 s . c o m
    OutputStream out = con.getOutputStream();
    try {
        out.write(body);
    } finally {
        out.close();
    }
    Assert.assertEquals(con.getResponseMessage(), 204, con.getResponseCode());
}

From source file:com.github.thorqin.webapi.oauth2.OAuthClient.java

public AccessToken refreshAccessToken(String authorityServerUri, String clientId, String clientSecret,
        String refreshToken, String scope) throws IOException, OAuthException {
    String content = "grant_type=refresh_token&refresh_token=" + URLEncoder.encode(refreshToken, "utf-8");
    if (scope != null && !scope.trim().isEmpty())
        content += "&scope=" + URLEncoder.encode(scope, "utf-8");
    String type = "application/x-www-form-urlencoded";
    URL u = new URL(authorityServerUri);
    HttpURLConnection conn = (HttpURLConnection) u.openConnection();
    conn.setDoOutput(true);//from  w  w w  .ja v  a 2  s  .  c  o m
    String basicAuthentication = Base64.encodeBase64String((clientId + ":" + clientSecret).getBytes());
    conn.setRequestProperty("Authorization", "Basic " + basicAuthentication);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", type);
    conn.setRequestProperty("Content-Length", String.valueOf(content.length()));
    try (OutputStream os = conn.getOutputStream()) {
        os.write(content.getBytes());
    }
    try (InputStream is = conn.getInputStream(); InputStreamReader reader = new InputStreamReader(is)) {
        AccessTokenResponse token = Serializer.fromJson(reader, AccessTokenResponse.class);
        if (token.error != null) {
            throw new OAuthException(token.error, token.errorDescription, token.errorUri);
        }
        return token;
    }
}

From source file:com.vuzix.samplewebrtc.android.SessionChannel.java

public void send(final Peer peer, final JSONObject message) {
    mSendHandler.post(new Runnable() {
        @Override//from  w  w  w . j a v a  2  s  . c  o  m
        public void run() {
            if (peer.mDisconnected) {
                return;
            }

            HttpURLConnection urlConnection = null;
            try {
                urlConnection = (HttpURLConnection) new URL(peer.mPeerUrl).openConnection();
                urlConnection.setRequestMethod("POST");
                urlConnection.setDoOutput(true);

                OutputStream os = urlConnection.getOutputStream();
                os.write(message.toString().getBytes("UTF-8"));
                os.flush();
                os.close();

                int responseCode = urlConnection.getResponseCode();
                if (responseCode != HttpURLConnection.HTTP_NO_CONTENT) {
                    Log.e(TAG, "response " + responseCode);
                }

            } catch (IOException e) {
                Log.e(TAG, "IOException", e);
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
            }
        }
    });
}