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:au.com.tyo.sn.shortener.GooGl.java

private static String post(String url) {
    HttpURLConnection httpcon = null;

    try {//from w  ww.  j  av  a 2  s . com
        httpcon = (HttpURLConnection) ((new URL(GOO_GL_REQUEST_URL).openConnection()));

        httpcon.setDoOutput(true);
        httpcon.setRequestProperty("Content-Type", "application/json");
        httpcon.setRequestProperty("Accept", "application/json");
        httpcon.setRequestMethod("POST");
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    byte[] outputBytes = { 0 };
    OutputStream os = null;
    InputStream is = null;
    BufferedReader in = null;
    StringBuilder text = new StringBuilder();

    try {
        outputBytes = ("{'longUrl': \"" + url + "\"}").getBytes("UTF-8");
        httpcon.setRequestProperty("Content-Length", Integer.toString(outputBytes.length));
        httpcon.connect();
        os = httpcon.getOutputStream();
        os.write(outputBytes);
        is = httpcon.getInputStream();
        in = new BufferedReader(new InputStreamReader(is, "UTF-8"));

        if (in != null) {
            // get page text
            String line;

            while ((line = in.readLine()) != null) {
                text.append(line);
                text.append("\n");
            }
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (os != null)
                os.close();
            if (is != null)
                is.close();
            if (in != null)
                in.close();
        } catch (IOException e) {
        }
    }

    return text.toString();
}

From source file:manchester.synbiochem.datacapture.SeekConnector.java

private static Status postForm(HttpURLConnection c, MultipartFormData form) throws IOException {
    c.setInstanceFollowRedirects(false);
    c.setDoOutput(true);//from   w  w  w  . j  a v  a 2 s. c  o m
    c.setRequestMethod("POST");
    c.setRequestProperty("Content-Type", form.contentType());
    c.setRequestProperty("Content-Length", form.length());
    c.connect();
    try (OutputStream os = c.getOutputStream()) {
        os.write(form.content());
    }
    return fromStatusCode(c.getResponseCode());
}

From source file:org.grameenfoundation.consulteca.utils.HttpHelpers.java

/**
 * Does an HTTP post for a given form data string.
 *
 * @param data is the form data string.//from   w w w  .  j ava2s  .c om
 * @param url  is the url to post to.
 * @return the return string from the server.
 * @throws java.io.IOException
 */
public static String postData(String data, URL url) throws IOException {

    String result = null;

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    try {
        HttpHelpers.addCommonHeaders(conn);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setConnectTimeout(HttpHelpers.NETWORK_TIMEOUT);
        conn.setReadTimeout(HttpHelpers.NETWORK_TIMEOUT);
        conn.setRequestProperty("Content-Length", "" + Integer.toString(data.getBytes().length));

        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

        writer.write(data);
        writer.flush();
        writer.close();

        String line;
        BufferedReader reader = (BufferedReader) getUncompressedResponseReader(conn);
        while ((line = reader.readLine()) != null) {
            if (result == null)
                result = line;
            else
                result += line;
        }

        reader.close();
    } catch (IOException ex) {
        Log.e(TAG, "Failed to read stream data", ex);

        String error = null;

        // TODO Am not yet sure if the section below should make it in the production release.
        // I mainly use it to get details of a failed http request. I get a FileNotFoundException
        // when actually the url is correct but an exception was thrown at the server and i use this
        // to get the server call stack for debugging purposes.
        try {
            String line;
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
            while ((line = reader.readLine()) != null) {
                if (error == null)
                    error = line;
                else
                    error += line;
            }

            reader.close();
        } catch (Exception e) {
            Log.e(TAG, "Problem encountered while trying to get error information:" + error, ex);
        }
    }

    return result;
}

From source file:com.gmobi.poponews.util.HttpHelper.java

private static Response doRequest(String url, Object raw, int method) {
    disableSslCheck();// w w w  .  j  a  v a2 s.  c om
    boolean isJson = raw instanceof JSONObject;
    String body = raw == null ? null : raw.toString();
    Response response = new Response();
    HttpURLConnection connection = null;
    try {
        URL httpURL = new URL(url);
        connection = (HttpURLConnection) httpURL.openConnection();
        connection.setConnectTimeout(15000);
        connection.setReadTimeout(30000);
        connection.setUseCaches(false);
        if (method == HTTP_POST)
            connection.setRequestMethod("POST");
        if (body != null) {
            if (isJson) {
                connection.setRequestProperty("Accept", "application/json");
                connection.setRequestProperty("Content-Type", "application/json");
            }
            OutputStream os = connection.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os);
            osw.write(body);
            osw.flush();
            osw.close();
        }
        InputStream in = connection.getInputStream();
        response.setBody(FileHelper.readText(in, "UTF-8"));
        response.setStatusCode(connection.getResponseCode());
        in.close();
        connection.disconnect();
        connection = null;
    } catch (Exception e) {
        Logger.error(e);
        try {
            if ((connection != null) && (response.getBody() == null) && (connection.getErrorStream() != null)) {
                response.setBody(FileHelper.readText(connection.getErrorStream(), "UTF-8"));
            }
        } catch (Exception ex) {
            Logger.error(ex);
        }
    }
    return response;
}

From source file:com.mingsoft.weixin.http.HttpClientConnectionManager.java

/**
 * ?//  w  w  w  . j  a v  a  2s.  com
 * @param postUrl ?
 * @param param ?
 * @param method 
 * @return null
 */
public static String request(String postUrl, String param, String method) {
    URL url;
    try {
        url = new URL(postUrl);

        HttpURLConnection conn;
        conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(30000); // ??)
        conn.setReadTimeout(30000); // ????)
        conn.setDoOutput(true); // post??http?truefalse
        conn.setDoInput(true); // ?httpUrlConnectiontrue
        conn.setUseCaches(false); // Post ?
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestMethod(method);// "POST"GET
        conn.setRequestProperty("Content-Length", param.length() + "");
        String encode = "utf-8";
        OutputStreamWriter out = null;
        out = new OutputStreamWriter(conn.getOutputStream(), encode);
        out.write(param);
        out.flush();

        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            return null;
        }
        // ??
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        String line = "";
        StringBuffer strBuf = new StringBuffer();
        while ((line = in.readLine()) != null) {
            strBuf.append(line).append("\n");
        }
        in.close();
        out.close();
        return strBuf.toString();
    } catch (MalformedURLException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

From source file:com.hippo.httpclient.JsonPoster.java

@Override
public void onOutput(HttpURLConnection conn) throws Exception {
    super.onOutput(conn);

    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
    out.write(mJSON.toString().getBytes("utf-8"));
    out.flush();/*from  ww  w  .j av  a 2 s  . com*/
    out.close();
}

From source file:com.cloudera.nav.sdk.client.writer.MetadataWriterFactory.java

/**
 * Create a new metadata writer//from w ww . j  av  a 2 s. c  om
 */
public MetadataWriter newWriter() {
    try {
        HttpURLConnection conn = createHttpStream();
        OutputStream stream = new BufferedOutputStream(conn.getOutputStream());
        return new JsonMetadataWriter(config, stream, conn);
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}

From source file:org.wso2.carbon.appmanager.integration.ui.Util.HttpUtil.java

public static HttpResponse doPut(URL endpoint, String postBody, Map<String, String> headers) throws Exception {
    HttpURLConnection urlConnection = null;
    try {/*from  w  w  w  .  j a  va  2 s. co m*/
        urlConnection = (HttpURLConnection) endpoint.openConnection();
        try {
            urlConnection.setRequestMethod("PUT");
        } catch (ProtocolException e) {
            throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e);
        }
        urlConnection.setDoOutput(true);

        if (headers != null && headers.size() > 0) {
            Iterator<String> itr = headers.keySet().iterator();
            while (itr.hasNext()) {
                String key = itr.next();
                urlConnection.setRequestProperty(key, headers.get(key));
            }
        }
        OutputStream out = urlConnection.getOutputStream();
        try {
            Writer writer = new OutputStreamWriter(out, "UTF-8");
            writer.write(postBody);
            writer.close();
        } catch (IOException e) {
            throw new Exception("IOException while puting data", e);
        } finally {
            if (out != null) {
                out.close();
            }
        }

        // Get the response
        StringBuilder sb = new StringBuilder();
        BufferedReader rd = null;
        try {
            rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
        } catch (FileNotFoundException ignored) {
        } finally {
            if (rd != null) {
                rd.close();
            }
        }
        Iterator<String> itr = urlConnection.getHeaderFields().keySet().iterator();
        Map<String, String> responseHeaders = new HashMap();
        while (itr.hasNext()) {
            String key = itr.next();
            if (key != null) {
                responseHeaders.put(key, urlConnection.getHeaderField(key));
            }
        }
        return new HttpResponse(sb.toString(), urlConnection.getResponseCode(), responseHeaders);

    } catch (IOException e) {
        throw new Exception("Connection error (is server running at " + endpoint + " ?): " + e);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}

From source file:com.expertiseandroid.lib.sociallib.utils.Utils.java

/**
 * Sends a POST request with an attached object
 * @param url the url that should be opened
 * @param params the body parameters/* w  ww . j  a v  a 2 s  .c o m*/
 * @param attachment the object to be attached
 * @return the response
 * @throws IOException
 */
public static String postWithAttachment(String url, Map<String, String> params, Object attachment)
        throws IOException {
    String boundary = generateBoundaryString(10);
    URL servUrl = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) servUrl.openConnection();
    conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + SOCIALLIB);
    conn.setRequestMethod("POST");
    String contentType = "multipart/form-data; boundary=" + boundary;
    conn.setRequestProperty("Content-Type", contentType);

    byte[] body = generatePostBody(params, attachment, boundary);

    conn.setDoOutput(true);
    conn.connect();
    OutputStream out = conn.getOutputStream();
    out.write(body);
    InputStream is = null;
    try {
        is = conn.getInputStream();
    } catch (FileNotFoundException e) {
        is = conn.getErrorStream();
    } catch (Exception e) {
        int statusCode = conn.getResponseCode();
        Log.e("Response code", "" + statusCode);
        return conn.getResponseMessage();
    }

    BufferedReader r = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    String l;
    while ((l = r.readLine()) != null)
        sb.append(l).append('\n');
    out.close();
    is.close();
    if (conn != null)
        conn.disconnect();
    return sb.toString();
}

From source file:com.forgerock.wisdom.oauth2.info.internal.StandardIntrospectionService.java

@Override
public TokenInfo introspect(final String token) {

    try {//ww w. jav a2s . c o  m
        HttpURLConnection connection = (HttpURLConnection) new URL(baseUrl).openConnection();
        connection.getOutputStream().write(format("token=%s", token).getBytes());
        connection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setDoOutput(true);
        if (bearerToken != null) {
            connection.addRequestProperty("Authorization", format("Bearer %s", bearerToken));
        }
        int code = connection.getResponseCode();
        if (code != 200) {
            return TokenInfo.INVALID;
        }

        try (InputStream stream = connection.getInputStream()) {
            JsonNode node = mapper.readTree(stream);
            if (node.get("active").asBoolean()) {

                JsonNode exp = node.get("exp");
                long expiresIn = 0;
                if (exp != null) {
                    expiresIn = exp.asLong() - System.currentTimeMillis();
                }

                JsonNode scope = node.get("scope");
                String[] scopes = null;
                if (scope != null) {
                    scopes = scope.asText().split(" ");
                }

                return new TokenInfo(true, expiresIn, scopes);
            }
        }

    } catch (IOException e) {
        // Ignored
    }

    return TokenInfo.INVALID;
}