Example usage for java.net HttpURLConnection setDoOutput

List of usage examples for java.net HttpURLConnection setDoOutput

Introduction

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

Prototype

public void setDoOutput(boolean dooutput) 

Source Link

Document

Sets the value of the doOutput field for this URLConnection to the specified value.

Usage

From source file:br.gov.jfrj.siga.base.ConexaoHTTP.java

public static String get(String URL, HashMap<String, String> header, Integer timeout, String payload)
        throws AplicacaoException {

    try {/*from  w ww .java  2 s .  c  om*/

        HttpURLConnection conn = (HttpURLConnection) new URL(URL).openConnection();

        if (timeout != null) {
            conn.setConnectTimeout(timeout);
            conn.setReadTimeout(timeout);
        }

        //conn.setInstanceFollowRedirects(true);

        if (header != null) {
            for (String s : header.keySet()) {
                conn.setRequestProperty(s, header.get(s));
            }
        }

        System.setProperty("http.keepAlive", "false");

        if (payload != null) {
            byte ab[] = payload.getBytes("UTF-8");
            conn.setRequestMethod("POST");
            // Send post request
            conn.setDoOutput(true);
            OutputStream os = conn.getOutputStream();
            os.write(ab);
            os.flush();
            os.close();
        }

        //StringWriter writer = new StringWriter();
        //IOUtils.copy(conn.getInputStream(), writer, "UTF-8");
        //return writer.toString();
        return IOUtils.toString(conn.getInputStream(), "UTF-8");

    } catch (IOException ioe) {
        throw new AplicacaoException("No foi possvel abrir conexo", 1, ioe);
    }

}

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

public static HttpResponse doPost(URL endpoint, String postBody, Map<String, String> headers) throws Exception {
    HttpURLConnection urlConnection = null;
    try {/*from www  . ja  va  2s. c  o  m*/
        urlConnection = (HttpURLConnection) endpoint.openConnection();
        try {
            urlConnection.setRequestMethod("POST");
        } catch (ProtocolException e) {
            throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e);
        }
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setUseCaches(false);
        urlConnection.setAllowUserInteraction(false);

        // setting headers
        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 posting 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.androidex.volley.toolbox.HurlStack.java

private static void addBodyIfExists(HttpURLConnection connection, Request<?> request)
        throws IOException, AuthFailureError {
    byte[] body = request.getBody();
    if (body != null) {
        ProgressListener progressListener = null;
        if (request instanceof ProgressListener) {
            progressListener = (ProgressListener) request;
        }//from ww  w  .ja  v a2  s .com
        connection.setDoOutput(true);
        connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType());
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());

        if (progressListener != null) {
            int transferredBytes = 0;
            int totalSize = body.length;
            int offset = 0;
            int chunkSize = Math.min(2048, Math.max(totalSize - offset, 0));
            while (chunkSize > 0 && offset + chunkSize <= totalSize) {
                out.write(body, offset, chunkSize);
                transferredBytes += chunkSize;
                progressListener.onProgress(transferredBytes, totalSize);
                offset += chunkSize;
                chunkSize = Math.min(chunkSize, Math.max(totalSize - offset, 0));
            }
        } else {
            out.write(body);
        }

        out.close();
    }
}

From source file:com.createtank.payments.coinbase.RequestClient.java

private static JsonObject call(CoinbaseApi api, String method, RequestVerb verb, Map<String, String> params,
        boolean retry, String accessToken) throws IOException {
    if (api.allowSecure()) {

        HttpClient client = HttpClientBuilder.create().build();
        String url = BASE_URL + method;
        HttpUriRequest request = null;/* w  w w. j  a  v  a2 s  . c  o  m*/

        if (verb == RequestVerb.POST || verb == RequestVerb.PUT) {
            switch (verb) {
            case POST:
                request = new HttpPost(url);
                break;
            case PUT:
                request = new HttpPut(url);
                break;
            default:
                throw new RuntimeException("RequestVerb not implemented: " + verb);
            }

            List<BasicNameValuePair> paramsBody = new ArrayList<BasicNameValuePair>();

            if (params != null) {
                List<BasicNameValuePair> convertedParams = convertParams(params);
                paramsBody.addAll(convertedParams);
            }

            ((HttpEntityEnclosingRequestBase) request).setEntity(new UrlEncodedFormEntity(paramsBody, "UTF-8"));
        } else {
            if (params != null) {
                url = url + "?" + createRequestParams(params);
            }

            if (verb == RequestVerb.GET) {
                request = new HttpGet(url);
            } else if (verb == RequestVerb.DELETE) {
                request = new HttpDelete(url);
            }
        }
        if (request == null)
            return null;

        if (accessToken != null)
            request.addHeader("Authorization", String.format("Bearer %s", accessToken));
        System.out.println("auth header: " + request.getFirstHeader("Authorization"));
        HttpResponse response = client.execute(request);
        int code = response.getStatusLine().getStatusCode();

        if (code == 401) {
            if (retry) {
                api.refreshAccessToken();
                call(api, method, verb, params, false, api.getAccessToken());
            } else {
                throw new IOException("Account is no longer valid");
            }
        } else if (code != 200) {
            throw new IOException("HTTP response " + code + " to request " + method);
        }

        String responseString = EntityUtils.toString(response.getEntity());
        if (responseString.startsWith("[")) {
            // Is an array
            responseString = "{response:" + responseString + "}";
        }

        JsonParser parser = new JsonParser();
        JsonObject resp = (JsonObject) parser.parse(responseString);
        System.out.println(resp.toString());
        return resp;
    }

    String paramStr = createRequestParams(params);
    String url = BASE_URL + method;

    if (paramStr != null && verb == RequestVerb.GET || verb == RequestVerb.DELETE)
        url += "?" + paramStr;

    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestMethod(verb.name());

    if (accessToken != null)
        conn.setRequestProperty("Authorization", String.format("Bearer %s", accessToken));

    if (verb != RequestVerb.GET && verb != RequestVerb.DELETE && paramStr != null) {
        conn.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
        writer.write(paramStr);
        writer.flush();
        writer.close();
    }

    int code = conn.getResponseCode();
    if (code == 401) {

        if (retry) {
            api.refreshAccessToken();
            return call(api, method, verb, params, false, api.getAccessToken());
        } else {
            throw new IOException("Account is no longer valid");
        }

    } else if (code != 200) {
        throw new IOException("HTTP response " + code + " to request " + method);
    }

    String responseString = getResponseBody(conn.getInputStream());
    if (responseString.startsWith("[")) {
        responseString = "{response:" + responseString + "}";
    }

    JsonParser parser = new JsonParser();
    return (JsonObject) parser.parse(responseString);
}

From source file:crow.util.Util.java

public static String urlPost(HttpURLConnection conn, String encodePostParam) throws IOException {
    int responseCode = -1;
    OutputStream osw = null;/*from  w  w w .  j a  va 2  s  .  c o  m*/
    try {
        conn.setConnectTimeout(20000);
        conn.setReadTimeout(12000);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setDoOutput(true);
        byte[] bytes = encodePostParam.getBytes("UTF-8");
        conn.setRequestProperty("Content-Length", Integer.toString(bytes.length));
        osw = conn.getOutputStream();
        osw.write(bytes);
        osw.flush();
        responseCode = conn.getResponseCode();
        if (responseCode != HttpURLConnection.HTTP_OK) {
            throw new IOException("");
        } else {
            String s = inputStreamToString(conn.getInputStream());
            return s;
        }
    } finally {
        try {
            if (osw != null)
                osw.close();
        } catch (Exception ignore) {
        }
    }
}

From source file:disko.DU.java

public static String request(String targetUrl, String method, String text, String contentType)
        throws Exception {
    URL url = new URL(targetUrl);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    if (method != null)
        conn.setRequestMethod(method);//from  w  w w.j av  a2  s  .c o m

    if (contentType != null)
        conn.setRequestProperty("Content-Type", contentType);

    if (text != null) {
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.getOutputStream().write(text.getBytes());
        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        out.write(text.getBytes());
        out.flush();
        out.close();
    }

    if (conn.getResponseCode() != 200)
        throw new RuntimeException("HTTPClient failed: " + conn.getResponseCode());

    StringBuffer responseBuffer = new StringBuffer();
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;
    String eol = new String(new byte[] { 13 });
    while ((line = in.readLine()) != null) {
        responseBuffer.append(line);
        responseBuffer.append(eol);
    }
    in.close();

    return responseBuffer.toString();
}

From source file:com.iStudy.Study.Renren.Util.java

private static HttpURLConnection openConn(String url, String method, Bundle params) {
    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }//from  www . ja va 2 s.c om
    try {
        Log.d(LOG_TAG, method + " URL: " + url);
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestProperty("User-Agent", USER_AGENT_SDK);
        if (!method.equals("GET")) {
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.getOutputStream().write(encodeUrl(params).getBytes("UTF-8"));
        }
        return conn;
    } catch (Exception e) {
        Log.e(LOG_TAG, e.getMessage());
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:com.iStudy.Study.Renren.Util.java

/**
 * ??http/*w  ww. j  av  a  2 s .c  o  m*/
 * 
 * @param url
 * @param method GET  POST
 * @param params
 * @return
 */
public static String openUrl(String url, String method, Bundle params) {
    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }
    String response = "";
    try {
        Log.d(LOG_TAG, method + " URL: " + url);
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestProperty("User-Agent", USER_AGENT_SDK);
        if (!method.equals("GET")) {
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.getOutputStream().write(encodeUrl(params).getBytes("UTF-8"));
        }

        InputStream is = null;
        int responseCode = conn.getResponseCode();
        if (responseCode == 200) {
            is = conn.getInputStream();
        } else {
            is = conn.getErrorStream();
        }
        response = read(is);
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    return response;
}

From source file:com.navercorp.volleyextensions.volleyer.multipart.stack.MultipartHurlStack.java

/**
 * <pre>/*from  ww w.  ja va  2  s  .c  o m*/
 * Add a multipart and write it to output of a connection.
 *
 * NOTE : It only supports chunked transfer encoding mode,
 *        the server should supports it.
 * </pre>
 */
private static void addMultipartIfExists(HttpURLConnection connection, Request<?> request)
        throws IOException, AuthFailureError {
    OutputStream os = null;
    try {
        if (!(request instanceof MultipartContainer)) {
            return;
        }

        MultipartContainer container = (MultipartContainer) request;
        if (!container.hasMultipart()) {
            return;
        }

        Multipart multipart = container.getMultipart();
        if (multipart == null) {
            return;
        }

        connection.setDoOutput(true);
        connection.addRequestProperty("Content-Type", multipart.getContentType());
        // Set chunked encoding mode.
        connection.setChunkedStreamingMode(DEFAULT_CHUNK_LENGTH);
        os = connection.getOutputStream();
        multipart.write(os);
        os.flush();
    } finally {
        if (os != null) {
            os.close();
        }
    }
}

From source file:com.screenslicer.common.CommonUtil.java

public static void postQuickly(String uri, String recipient, String postData) {
    HttpURLConnection conn = null;
    try {//  www .j  a  v  a 2s. com
        postData = Crypto.encode(postData, recipient);
        conn = (HttpURLConnection) new URL(uri).openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json");
        byte[] bytes = postData.getBytes("utf-8");
        conn.setRequestProperty("Content-Length", String.valueOf(bytes.length));
        OutputStream os = conn.getOutputStream();
        os.write(bytes);
        conn.connect();
        Crypto.decode(IOUtils.toString(conn.getInputStream(), "utf-8"), recipient);
    } catch (Exception e) {
        Log.exception(e);
    }
}