Example usage for java.net HttpURLConnection setDoInput

List of usage examples for java.net HttpURLConnection setDoInput

Introduction

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

Prototype

public void setDoInput(boolean doinput) 

Source Link

Document

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

Usage

From source file:com.vimc.ahttp.HurlWorker.java

/**
 * Opens an {@link HttpURLConnection} with parameters.
 * //  w  ww  . ja  v a 2s.c o  m
 * @param url
 * @return an open connection
 * @throws IOException
 */
private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException {
    HttpURLConnection connection = createConnection(url);

    connection.setConnectTimeout(request.connectTimeout);
    connection.setReadTimeout(request.soTimeout);
    connection.setUseCaches(false);
    connection.setDoInput(true);
    // connection.setRequestProperty("Connection", "close");

    if ("https".equals(url.getProtocol())) {
        if (mSslSocketFactory != null) {
            ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory);
        } else {
            setDefaultSSLSocketFactory();
        }
    }

    return connection;
}

From source file:com.jeffrodriguez.webtools.client.URLConnectionWebClientImpl.java

@Override
public byte[] post(String url, byte[] data, Map<String, List<String>> headers) throws IOException {

    // Build and connect
    HttpURLConnection connection = buildConnection(url);
    applyHeaders(connection, headers);/*from   w  ww  .j  ava2 s  .c o  m*/
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.connect();

    // Send the request
    connection.getOutputStream().write(data);
    connection.getOutputStream().flush();
    connection.getOutputStream().close();

    // Check for errors
    checkForErrors(connection);

    // Get the result
    return disconnectAndReturn(connection, IOUtils.toByteArray(connection.getInputStream()));
}

From source file:com.iflytek.android.framework.volley.toolbox.HurlStack.java

/**
 * Opens an {@link HttpURLConnection} with parameters.
 * //from  w  w  w .  ja v a2s  . c  o m
 * @param url
 * @return an open connection
 * @throws IOException
 */
private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException {
    HttpURLConnection connection = createConnection(url);

    int timeoutMs = request.getTimeoutMs();

    connection.setConnectTimeout(timeoutMs);
    connection.setReadTimeout(timeoutMs);
    connection.setUseCaches(false);
    connection.setDoInput(true);

    // use caller-provided custom SslSocketFactory, if any, for HTTPS
    if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) {
        ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory);
    }

    return connection;
}

From source file:api.wireless.gdata.client.TokenFactory.java

/**
 * Makes a HTTP POST request to the provided {@code url} given the
 * provided {@code parameters}.  It returns the output from the POST
 * handler as a String object.//from  w ww . j  a  va  2s  . c o m
 *
 * @param url the URL to post the request
 * @param parameters the parameters to post to the handler
 * @return the output from the handler
 * @throws IOException if an I/O exception occurs while creating, writing,
 *                     or reading the request
 */
public String makePostRequest(URL url, Map<String, String> parameters) throws IOException {

    // Open connection      
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

    // Set properties of the connection
    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(true);
    urlConnection.setUseCaches(false);
    urlConnection.setRequestMethod("POST");
    urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    // Form the POST parameters
    StringBuilder content = new StringBuilder();
    boolean first = true;
    for (Map.Entry<String, String> parameter : parameters.entrySet()) {
        if (!first) {
            content.append("&");
        }
        content.append(CharEscapers.uriEscaper().escape(parameter.getKey())).append("=");
        content.append(CharEscapers.uriEscaper().escape(parameter.getValue()));
        first = false;
    }

    OutputStream outputStream = null;
    try {
        outputStream = urlConnection.getOutputStream();
        outputStream.write(content.toString().getBytes("utf-8"));
        outputStream.flush();
    } finally {
        if (outputStream != null) {
            outputStream.close();
        }
    }

    // Retrieve the output
    InputStream inputStream = null;
    StringBuilder outputBuilder = new StringBuilder();
    try {
        int responseCode = urlConnection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            inputStream = urlConnection.getInputStream();
        } else {
            inputStream = urlConnection.getErrorStream();
        }

        String string;
        if (inputStream != null) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            while (null != (string = reader.readLine())) {
                outputBuilder.append(string).append('\n');
            }
        }
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
    }
    return outputBuilder.toString();
}

From source file:com.github.hipchat.api.HipChat.java

private HttpURLConnection getGetConnection(URL requestUrl) {
    HttpURLConnection connection = null;
    try {/*w w  w  . jav  a  2s . c o m*/
        connection = (HttpURLConnection) requestUrl.openConnection();
        connection.setDoInput(true);
    } catch (IOException e) {
        LogMF.error(logger, "IO Exception: {0}", new Object[] { e.getMessage() });
    }
    return connection;
}

From source file:com.informatica.um.binge.api.impl.PluginsFactory.java

private InputStream getInputStream(String urlstr) throws VDSException {
    HttpURLConnection con = null;
    URL url;//from  w w  w  .j a  va2  s . com
    try {
        url = new URL(urlstr);
        con = (HttpURLConnection) url.openConnection();
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setRequestMethod("GET");
        con.setUseCaches(false);
        con.connect();
        return con.getInputStream();
    } catch (MalformedURLException e) {
        throw new VDSException(VDSErrorCode.MALFORMED_ADMIND_URL, e, urlstr);
    } catch (IOException e) {
        throw new VDSException(VDSErrorCode.ADMIND_CONNECTION_ERROR, e, urlstr);
    }
}

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

public String doJsonRequest(String request, String data, String method)
        throws MalformedURLException, IOException {
    URL path = new URL(ADDRESS + request);
    HttpURLConnection conn = (HttpURLConnection) path.openConnection();
    conn.setRequestMethod(method);//from www .j av  a 2s  . c o m
    conn.setRequestProperty("Content-Type", "application/json");
    conn.setRequestProperty("Content-Length ", Integer.toString(data.length()));
    conn.setRequestProperty("AppKey", KEY);
    conn.setUseCaches(false);
    conn.setDoInput(true);
    if (data.length() != 0) {
        conn.setDoOutput(true);
        OutputStream output = conn.getOutputStream();
        output.write(data.getBytes("UTF-8"));
        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 (String) response.toString();
}

From source file:io.confluent.kafkarest.tools.ConsumerPerformance.java

private <T> T request(String target, String method, byte[] entity, String entityLength,
        TypeReference<T> responseFormat) {
    HttpURLConnection connection = null;
    try {//  www .  j  av  a2  s .c  o  m
        URL url = new URL(target);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod(method);
        if (entity != null) {
            connection.setRequestProperty("Content-Type", Versions.KAFKA_MOST_SPECIFIC_DEFAULT);
            connection.setRequestProperty("Content-Length", entityLength);
        }
        connection.setDoInput(true);
        connection.setUseCaches(false);
        if (entity != null) {
            connection.setDoOutput(true);
            OutputStream os = connection.getOutputStream();
            os.write(entity);
            os.flush();
            os.close();
        }

        int responseStatus = connection.getResponseCode();
        if (responseStatus >= 400) {
            InputStream es = connection.getErrorStream();
            ErrorMessage errorMessage = jsonDeserializer.readValue(es, ErrorMessage.class);
            es.close();
            throw new RuntimeException(String.format("Unexpected HTTP error status %d for %s request to %s: %s",
                    responseStatus, method, target, errorMessage.getMessage()));
        }
        if (responseStatus != HttpURLConnection.HTTP_NO_CONTENT) {
            InputStream is = connection.getInputStream();
            T result = serializer.readValue(is, responseFormat);
            is.close();
            return result;
        }
        return null;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:org.wisdom.openid.connect.service.internal.DefaultIssuer.java

@Override
public TokenResponse authorizationToken(final String redirectUrl, final String code) throws IOException {

    StringBuilder sb = new StringBuilder();
    sb.append("grant_type=authorization_code");
    sb.append(format("&code=%s", code));
    sb.append(format("&client_id=%s", clientId));
    sb.append(format("&client_secret=%s", clientSecret));
    sb.append(format("&redirect_uri=%s", redirectUrl));

    String parameters = sb.toString();

    URL tokenEndpoint = new URL(config.getTokenEndpoint());
    HttpURLConnection connection = (HttpURLConnection) tokenEndpoint.openConnection();
    connection.setRequestMethod("POST");
    connection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    //connection.addRequestProperty("Authorization", format("Basic %s", credentials()));
    connection.setRequestProperty("Content-Length", valueOf(parameters.getBytes().length));

    connection.setUseCaches(false);//from w w w . j a  va  2 s  .c  o m
    connection.setDoInput(true);
    connection.setDoOutput(true);

    //Send request
    DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
    wr.writeBytes(parameters);
    wr.flush();
    wr.close();

    //Get Response
    return buildTokenResponse(connection.getInputStream());
}

From source file:com.footprint.cordova.plugin.localnotification.Options.java

/**
 * Converts an Image URL to Bitmap./*from   w  w  w  .  j a va 2s. c  o  m*/
 *
 * @param src
 *      The external image URL
 * @return
 *      The corresponding bitmap
 */
private Bitmap getIconFromURL(String src) {
    Bitmap bmp = null;
    ThreadPolicy origMode = StrictMode.getThreadPolicy();

    try {
        URL url = new URL(src);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

        StrictMode.setThreadPolicy(policy);

        connection.setDoInput(true);
        connection.connect();

        InputStream input = connection.getInputStream();

        bmp = BitmapFactory.decodeStream(input);
    } catch (Exception e) {
        e.printStackTrace();
    }

    StrictMode.setThreadPolicy(origMode);

    return bmp;
}