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.spoiledmilk.ibikecph.util.HttpUtils.java

public static JsonResult readLink(String url_string, String method) {
    JsonResult result = new JsonResult();
    if (url_string == null) {
        return result;
    }//w ww  . ja v  a2s  . co  m
    URL url = null;
    HttpURLConnection httpget = null;
    try {
        LOG.d("HttpUtils readlink() " + url_string);
        url = new URL(url_string);
        httpget = (HttpURLConnection) url.openConnection();
        httpget.setDoInput(true);
        httpget.setRequestMethod(method);
        httpget.setRequestProperty("Accept", "application/json");
        httpget.setRequestProperty("Content-type", "application/json");
        httpget.setConnectTimeout(CONNECTON_TIMEOUT);
        httpget.setReadTimeout(CONNECTON_TIMEOUT);
        JsonNode root = null;
        root = Util.getJsonObjectMapper().readValue(httpget.getInputStream(), JsonNode.class);
        if (root != null) {
            result.setNode(root);
        }
    } catch (JsonParseException e) {
        LOG.w("HttpUtils readLink() JsonParseException ", e);
        result.error = JsonResult.ErrorCode.APIError;
    } catch (MalformedURLException e) {
        LOG.w("HttpUtils readLink() MalformedURLException", e);
        result.error = JsonResult.ErrorCode.APIError;
    } catch (FileNotFoundException e) {
        LOG.w("HttpUtils readLink() FileNotFoundException", e);
        result.error = JsonResult.ErrorCode.NotFound;
    } catch (IOException e) {
        LOG.w("HttpUtils readLink() IOException", e);
        result.error = JsonResult.ErrorCode.ConnectionError;
    } finally {
        if (httpget != null) {
            httpget.disconnect();
        }
    }
    LOG.d("HttpUtils readLink() "
            + (result != null && result.error == JsonResult.ErrorCode.Success ? "succeeded" : "failed"));
    return result;
}

From source file:com.hichengdai.qlqq.front.util.HttpKit.java

/**
 * //from www.j  av  a  2  s  .  c om
 * 
 * @param url
 * @param params
 * @param file
 * @return
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws KeyManagementException
 */
public static String upload(String url, File file)
        throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
    String BOUNDARY = "----WebKitFormBoundaryiDGnV9zdZA1eM1yL"; // ?
    StringBuffer bufferRes = null;
    URL urlGet = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) urlGet.openConnection();
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("connection", "Keep-Alive");
    conn.setRequestProperty("user-agent",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36");
    conn.setRequestProperty("Charsert", "UTF-8");
    conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

    OutputStream out = new DataOutputStream(conn.getOutputStream());
    byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();// ??
    StringBuilder sb = new StringBuilder();
    sb.append("--");
    sb.append(BOUNDARY);
    sb.append("\r\n");
    sb.append("Content-Disposition: form-data;name=\"media\";filename=\"" + file.getName() + "\"\r\n");
    sb.append("Content-Type:application/octet-stream\r\n\r\n");
    byte[] data = sb.toString().getBytes();
    out.write(data);
    DataInputStream fs = new DataInputStream(new FileInputStream(file));
    int bytes = 0;
    byte[] bufferOut = new byte[1024];
    while ((bytes = fs.read(bufferOut)) != -1) {
        out.write(bufferOut, 0, bytes);
    }
    out.write("\r\n".getBytes()); // 
    fs.close();
    out.write(end_data);
    out.flush();
    out.close();

    // BufferedReader???URL?
    InputStream in = conn.getInputStream();
    BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
    String valueString = null;
    bufferRes = new StringBuffer();
    while ((valueString = read.readLine()) != null) {
        bufferRes.append(valueString);
    }
    in.close();
    if (conn != null) {
        // 
        conn.disconnect();
    }
    return bufferRes.toString();
}

From source file:com.dmsl.anyplace.utils.NetworkUtils.java

public static InputStream downloadHttp(String urlS) throws URISyntaxException, IOException {
    InputStream is = null;//from  ww w.  j  a va 2  s  .c  o m

    URL url = new URL(encodeURL(urlS));

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(10000);
    conn.setConnectTimeout(15000);
    conn.setRequestMethod("GET");
    conn.setDoInput(true);

    conn.connect();

    int response = conn.getResponseCode();
    if (response == 200) {
        is = conn.getInputStream();
    }

    return is;
}

From source file:dlauncher.authorization.DefaultCredentialsManager.java

private static JSONObject makeRequest(URL url, JSONObject post, boolean ignoreErrors)
        throws ProtocolException, IOException, AuthorizationException {
    JSONObject obj = null;//from w ww  . j av a  2  s  . co  m
    try {
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setUseCaches(false);
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json");
        con.setConnectTimeout(15 * 1000);
        con.setReadTimeout(15 * 1000);
        con.connect();
        try (OutputStream out = con.getOutputStream()) {
            out.write(post.toString().getBytes(Charset.forName("UTF-8")));
        }
        con.getResponseCode();
        InputStream instr;
        instr = con.getErrorStream();
        if (instr == null) {
            instr = con.getInputStream();
        }
        byte[] data = new byte[1024];
        int length;
        try (SizeLimitedByteArrayOutputStream bytes = new SizeLimitedByteArrayOutputStream(1024 * 4)) {
            try (InputStream in = new BufferedInputStream(instr)) {
                while ((length = in.read(data)) >= 0) {
                    bytes.write(data, 0, length);
                }
            }
            byte[] rawBytes = bytes.toByteArray();
            if (rawBytes.length != 0) {
                obj = new JSONObject(new String(rawBytes, Charset.forName("UTF-8")));
            } else {
                obj = new JSONObject();
            }
            if (!ignoreErrors && obj.has("error")) {
                String error = obj.getString("error");
                String errorMessage = obj.getString("errorMessage");
                String cause = obj.optString("cause", null);
                if ("ForbiddenOperationException".equals(error)) {
                    if ("UserMigratedException".equals(cause)) {
                        throw new UserMigratedException(errorMessage);
                    }
                    throw new ForbiddenOperationException(errorMessage);
                }
                throw new AuthorizationException(
                        error + (cause != null ? "." + cause : "") + ": " + errorMessage);
            }
            return obj;
        }
    } catch (JSONException ex) {
        throw new InvalidResponseException(ex, obj);
    }
}

From source file:com.evilisn.DAO.CertMapper.java

public static byte[] httpGetBin(URI uri, boolean bActiveCheckUnknownHost) throws Exception

{

    InputStream is = null;/*from   ww w  . ja  va2s  .  c om*/

    InputStream is_temp = null;

    try {

        if (uri == null)
            return null;

        URL url = uri.toURL();

        if (bActiveCheckUnknownHost) {

            url.getProtocol();

            String host = url.getHost();

            int port = url.getPort();

            if (port == -1)

                port = url.getDefaultPort();

            InetSocketAddress isa = new InetSocketAddress(host, port);

            if (isa.isUnresolved()) {

                //fix JNLP popup error issue

                throw new UnknownHostException("Host Unknown:" + isa.toString());

            }

        }

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

        uc.setDoInput(true);

        uc.setAllowUserInteraction(false);

        uc.setInstanceFollowRedirects(true);

        setTimeout(uc);

        String contentEncoding = uc.getContentEncoding();

        int len = uc.getContentLength();

        // is = uc.getInputStream();

        if (contentEncoding != null && contentEncoding.toLowerCase().indexOf("gzip") != -1)

        {

            is_temp = uc.getInputStream();

            is = new GZIPInputStream(is_temp);

        }

        else if (contentEncoding != null && contentEncoding.toLowerCase().indexOf("deflate") != -1)

        {

            is_temp = uc.getInputStream();

            is = new InflaterInputStream(is_temp);

        }

        else

        {

            is = uc.getInputStream();

        }

        if (len != -1) {

            int ch = 0, i = 0;

            byte[] res = new byte[len];

            while ((ch = is.read()) != -1) {

                res[i++] = (byte) (ch & 0xff);

            }

            return res;

        } else {

            ArrayList<byte[]> buffer = new ArrayList<byte[]>();

            int buf_len = 1024;

            byte[] res = new byte[buf_len];

            int ch = 0, i = 0;

            while ((ch = is.read()) != -1) {

                res[i++] = (byte) (ch & 0xff);

                if (i == buf_len) {

                    //rotate

                    buffer.add(res);

                    i = 0;

                    res = new byte[buf_len];

                }

            }

            int total_len = buffer.size() * buf_len + i;

            byte[] buf = new byte[total_len];

            for (int j = 0; j < buffer.size(); j++) {

                System.arraycopy(buffer.get(j), 0, buf, j * buf_len, buf_len);

            }

            if (i > 0) {

                System.arraycopy(res, 0, buf, buffer.size() * buf_len, i);

            }

            return buf;

        }

    } catch (Exception e) {

        e.printStackTrace();

        return null;

    } finally {

        closeInputStream(is_temp);

        closeInputStream(is);

    }

}

From source file:flow.visibility.tapping.OpenDaylightHelper.java

/** The function for inserting the flow */

public static boolean installFlow(JSONObject postData, String user, String password, String baseURL) {

    StringBuffer result = new StringBuffer();

    /** Check the connection to ODP REST API page */

    try {//w ww .j ava 2 s . co m

        if (!baseURL.contains("http")) {
            baseURL = "http://" + baseURL;
        }
        baseURL = baseURL + "/controller/nb/v2/flowprogrammer/default/node/OF/"
                + postData.getJSONObject("node").get("id") + "/staticFlow/" + postData.get("name");

        /** Create URL = base URL + container */
        URL url = new URL(baseURL);

        /** Create authentication string and encode it to Base64*/
        String authStr = user + ":" + password;
        String encodedAuthStr = Base64.encodeBase64String(authStr.getBytes());

        /** Create Http connection */
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        /** Set connection properties */
        connection.setRequestMethod("PUT");
        connection.setRequestProperty("Authorization", "Basic " + encodedAuthStr);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        /** Set JSON Post Data */
        OutputStream os = connection.getOutputStream();
        os.write(postData.toString().getBytes());
        os.close();

        /** Get the response from connection's inputStream */
        InputStream content = (InputStream) connection.getInputStream();
        BufferedReader in = new BufferedReader(new InputStreamReader(content));
        String line = "";
        while ((line = in.readLine()) != null) {
            result.append(line);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    /** checking the result of REST API connection */

    if ("success".equalsIgnoreCase(result.toString())) {
        return true;
    } else {
        return false;
    }
}

From source file:brainleg.app.util.AppWeb.java

/**
 * Copied from ITNProxy//  w  w  w .  j a  v a  2  s .co m
 */
private static HttpURLConnection doPost(String url, byte[] bytes) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) HttpConfigurable.getInstance().openConnection(url);

    connection.setReadTimeout(60 * 1000);
    connection.setConnectTimeout(10 * 1000);
    connection.setRequestMethod(HTTP_POST);
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setRequestProperty(HTTP_CONTENT_TYPE, String.format("%s; charset=%s", HTTP_WWW_FORM, ENCODING));
    connection.setRequestProperty(HTTP_CONTENT_LENGTH, Integer.toString(bytes.length));

    OutputStream out = new BufferedOutputStream(connection.getOutputStream());
    try {
        out.write(bytes);
        out.flush();
    } finally {
        out.close();
    }

    return connection;
}

From source file:dk.kk.ibikecphlib.util.HttpUtils.java

public static JsonResult readLink(String urlString, String method, boolean breakRoute) {
    JsonResult result = new JsonResult();
    if (urlString == null) {
        return result;
    }//  w  ww .  ja v a  2  s.  c o  m
    URL url = null;
    HttpURLConnection httpget = null;
    try {
        LOG.d("HttpUtils readlink() " + urlString);
        url = new URL(urlString);
        httpget = (HttpURLConnection) url.openConnection();
        httpget.setDoInput(true);
        httpget.setRequestMethod(method);
        if (breakRoute) {
            httpget.setRequestProperty("Accept", "application/vnd.ibikecph.v1");
        } else {
            httpget.setRequestProperty("Accept", "application/json");
        }
        httpget.setConnectTimeout(CONNECTON_TIMEOUT);
        httpget.setReadTimeout(CONNECTON_TIMEOUT);
        JsonNode root = Util.getJsonObjectMapper().readValue(httpget.getInputStream(), JsonNode.class);
        if (root != null) {
            result.setNode(root);
        }
    } catch (JsonParseException e) {
        LOG.w("HttpUtils readLink() JsonParseException ", e);
        result.error = JsonResult.ErrorCode.APIError;
    } catch (MalformedURLException e) {
        LOG.w("HttpUtils readLink() MalformedURLException", e);
        result.error = JsonResult.ErrorCode.APIError;
    } catch (FileNotFoundException e) {
        LOG.w("HttpUtils readLink() FileNotFoundException", e);
        result.error = JsonResult.ErrorCode.NotFound;
    } catch (IOException e) {
        LOG.w("HttpUtils readLink() IOException", e);
        result.error = JsonResult.ErrorCode.ConnectionError;
    } catch (Exception e) {
    } finally {
        if (httpget != null) {
            httpget.disconnect();
        }
    }
    LOG.d("HttpUtils readLink() "
            + (result != null && result.error == JsonResult.ErrorCode.Success ? "succeeded" : "failed"));
    return result;
}

From source file:edu.jhu.cvrg.timeseriesstore.opentsdb.TimeSeriesUtility.java

private static HttpURLConnection openHTTPConnection(String urlString, HttpVerbs verb)
        throws MalformedURLException, IOException {
    URL url = null;//from  ww w  . j  a  va  2  s .c  o m
    HttpURLConnection conn = null;

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

    switch (verb) {
    case POST:
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        break;
    case PUT:
        conn.setRequestMethod("PUT");
        conn.setDoOutput(true);
        break;
    case DELETE:
        conn.setRequestMethod("DELETE");
        break;
    default:
        conn.setRequestMethod("GET");
        break;
    }

    conn.setRequestProperty("Accept", "application/json");
    conn.setRequestProperty("Content-type", "application/json");

    return conn;
}

From source file:com.codelanx.codelanxlib.util.auth.UUIDFetcher.java

/**
 * Opens the connection to Mojang's profile API
 * /*from ww  w  . ja va 2 s .c  om*/
 * @since 0.0.1
 * @version 0.0.1
 * 
 * @return The {@link HttpURLConnection} object to the API server
 * @throws IOException If there is a problem opening the stream, a malformed
 *                     URL, or if there is a ProtocolException
 */
private static HttpURLConnection createConnection() throws IOException {
    URL url = new URL(UUIDFetcher.PROFILE_URL);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/json");
    connection.setUseCaches(false);
    connection.setDoInput(true);
    connection.setDoOutput(true);
    return connection;
}