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:BihuHttpUtil.java

/**
 * ??HTTPJSON?/*from   w  w w  . j a v  a2s.co m*/
 * @param url
 * @param jsonStr
 */
public static String sendPostForJson(String url, String jsonStr) {
    StringBuffer sb = new StringBuffer("");
    try {
        //
        URL realUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        connection.connect();
        //POST
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.write(jsonStr.getBytes("UTF-8"));//???
        out.flush();
        out.close();
        //??
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String lines;
        while ((lines = reader.readLine()) != null) {
            lines = new String(lines.getBytes(), "utf-8");
            sb.append(lines);
        }
        reader.close();
        // 
        connection.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return sb.toString();
}

From source file:gribbit.util.RequestBuilder.java

/**
 * Make a GET or POST request, handling up to 6 redirects, and return the response. If isBinaryResponse is true,
 * returns a byte[] array, otherwise returns the response as a String.
 *///from  www .ja  va  2s . c  om
private static Object makeRequest(String url, String[] keyValuePairs, boolean isGET, boolean isBinaryResponse,
        int redirDepth) {
    if (redirDepth > 6) {
        throw new IllegalArgumentException("Too many redirects");
    }
    HttpURLConnection connection = null;
    try {
        // Add the URL query params if this is a GET request
        String reqURL = isGET ? url + "?" + WebUtils.buildQueryString(keyValuePairs) : url;
        connection = (HttpURLConnection) new URL(reqURL).openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod(isGET ? "GET" : "POST");
        connection.setUseCaches(false);
        connection.setRequestProperty("User-Agent",
                "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) "
                        + "Chrome/43.0.2357.125 Safari/537.36");
        if (!isGET) {
            // Send the body if this is a POST request
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("charset", "utf-8");
            String params = WebUtils.buildQueryString(keyValuePairs);
            connection.setRequestProperty("Content-Length", Integer.toString(params.length()));
            try (DataOutputStream w = new DataOutputStream(connection.getOutputStream())) {
                w.writeBytes(params);
                w.flush();
            }
        }
        if (connection.getResponseCode() == HttpResponseStatus.FOUND.code()) {
            // Follow a redirect. For safety, the params are not passed on, and the method is forced to GET.
            return makeRequest(connection.getHeaderField("Location"), /* keyValuePairs = */null, /* isGET = */
                    true, isBinaryResponse, redirDepth + 1);
        } else if (connection.getResponseCode() == HttpResponseStatus.OK.code()) {
            // For 200 OK, return the text of the response
            if (isBinaryResponse) {
                ByteArrayOutputStream output = new ByteArrayOutputStream(32768);
                IOUtils.copy(connection.getInputStream(), output);
                return output.toByteArray();
            } else {
                StringWriter writer = new StringWriter(1024);
                IOUtils.copy(connection.getInputStream(), writer, "UTF-8");
                return writer.toString();
            }
        } else {
            throw new IllegalArgumentException(
                    "Got non-OK HTTP response code: " + connection.getResponseCode());
        }
    } catch (Exception e) {
        throw new IllegalArgumentException(
                "Exception during " + (isGET ? "GET" : "POST") + " request: " + e.getMessage(), e);
    } finally {
        if (connection != null) {
            try {
                connection.disconnect();
            } catch (Exception e) {
            }
        }
    }
}

From source file:ee.ria.xroad.proxy.ProxyMain.java

private static Map<String, DiagnosticsStatus> checkConnectionToTimestampUrl() {
    Map<String, DiagnosticsStatus> statuses = new HashMap<>();

    for (String tspUrl : ServerConf.getTspUrl()) {
        try {//  www  .j av  a  2  s  . c  o  m
            URL url = new URL(tspUrl);

            log.info("Checking timestamp server status for url {}", url);

            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setConnectTimeout(DIAGNOSTICS_CONNECTION_TIMEOUT_MS);
            con.setReadTimeout(DIAGNOSTICS_READ_TIMEOUT_MS);
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-type", "application/timestamp-query");
            con.connect();

            log.info("Checking timestamp server con {}", con);

            if (con.getResponseCode() != HttpURLConnection.HTTP_OK) {
                log.warn("Timestamp check received HTTP error: {} - {}. Might still be ok",
                        con.getResponseCode(), con.getResponseMessage());
                statuses.put(tspUrl,
                        new DiagnosticsStatus(DiagnosticsErrorCodes.RETURN_SUCCESS, LocalTime.now(), tspUrl));
            } else {
                statuses.put(tspUrl,
                        new DiagnosticsStatus(DiagnosticsErrorCodes.RETURN_SUCCESS, LocalTime.now(), tspUrl));
            }

        } catch (Exception e) {
            log.warn("Timestamp status check failed {}", e);

            statuses.put(tspUrl,
                    new DiagnosticsStatus(DiagnosticsUtils.getErrorCode(e), LocalTime.now(), tspUrl));
        }
    }
    return statuses;

}

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

/**
 * ?//from   www  .ja  va  2  s  .c  om
 * @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:net.nym.library.http.UploadImagesRequest.java

/**
 * ???/*from  www .  ja v a2 s .com*/
 *
 * @param url
 *            Service net address
 * @param params
 *            text content
 * @param files
 *            pictures
 * @return String result of Service response
 * @throws java.io.IOException
 */
public static String postFile(String url, Map<String, Object> params, Map<String, File> files)
        throws IOException {
    String result = "";
    String BOUNDARY = UUID.randomUUID().toString();
    String PREFIX = "--", LINEND = "\r\n";
    String MULTIPART_FROM_DATA = "multipart/form-data";
    String CHARSET = "UTF-8";

    StringBuilder sb = new StringBuilder("?");
    for (Map.Entry<String, Object> entry : params.entrySet()) {
        //                sb.append(PREFIX);
        //                sb.append(BOUNDARY);
        //                sb.append(LINEND);
        //                sb.append("Content-Disposition: form-data; name=\""
        //                        + entry.getKey() + "\"" + LINEND);
        //                sb.append("Content-Type: text/plain; charset=" + CHARSET
        //                        + LINEND);
        //                sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
        //                sb.append(LINEND);
        //                sb.append(entry.getValue());
        //                sb.append(LINEND);
        //                String key = entry.getKey();
        //                sb.append("&");
        //                sb.append(key).append("=").append(params.get(key));
        //                Log.i("%s=%s",key,params.get(key).toString());
        sb.append(entry.getKey()).append("=").append(NetUtil.URLEncode(entry.getValue().toString()))
                .append("&");
    }
    sb.deleteCharAt(sb.length() - 1);
    URL uri = new URL(url + sb.toString());
    HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
    conn.setConnectTimeout(50000);
    conn.setDoInput(true);// ?
    conn.setDoOutput(true);// ?
    conn.setUseCaches(false); // ??
    conn.setRequestMethod("POST");
    conn.setRequestProperty("connection", "keep-alive");
    conn.setRequestProperty("Charsert", "UTF-8");
    conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
    // ?
    //            StringBuilder sb = new StringBuilder();
    //            for (Map.Entry<String, Object> entry : params.entrySet()) {
    ////                sb.append(PREFIX);
    ////                sb.append(BOUNDARY);
    ////                sb.append(LINEND);
    ////                sb.append("Content-Disposition: form-data; name=\""
    ////                        + entry.getKey() + "\"" + LINEND);
    ////                sb.append("Content-Type: text/plain; charset=" + CHARSET
    ////                        + LINEND);
    ////                sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
    ////                sb.append(LINEND);
    ////                sb.append(entry.getValue());
    ////                sb.append(LINEND);
    //                String key = entry.getKey();
    //                sb.append("&");
    //                sb.append(key).append("=").append(params.get(key));
    //                Log.i("%s=%s",key,params.get(key).toString());
    //            }

    DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
    //            outStream.write(sb.toString().getBytes());
    // ?
    if (files != null) {
        for (Map.Entry<String, File> file : files.entrySet()) {
            StringBuilder sbFile = new StringBuilder();
            sbFile.append(PREFIX);
            sbFile.append(BOUNDARY);
            sbFile.append(LINEND);
            /**
             * ?? name???key ?key ??
             * filename?????? :abc.png
             */
            sbFile.append("Content-Disposition: form-data; name=\"" + file.getKey() + "\"; filename=\""
                    + file.getValue().getName() + "\"" + LINEND);
            sbFile.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND);
            sbFile.append(LINEND);
            Log.i(sbFile.toString());
            outStream.write(sbFile.toString().getBytes());

            InputStream is = new FileInputStream(file.getValue());
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = is.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            is.close();
            outStream.write(LINEND.getBytes());
        }
        // ?
        byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
        outStream.write(end_data);
    }

    outStream.flush();
    // ??
    int res = conn.getResponseCode();
    InputStream in = conn.getInputStream();
    StringBuilder sbResult = new StringBuilder();
    if (res == 200) {
        int ch;
        while ((ch = in.read()) != -1) {
            sbResult.append((char) ch);
        }
    }
    result = sbResult.toString();
    outStream.close();
    conn.disconnect();
    return result;
}

From source file:com.chiorichan.util.WebUtils.java

/**
 * Establishes an HttpURLConnection from a URL, with the correct configuration to receive content from the given URL.
 * //from  w w  w . j  av  a  2 s  .  c  o m
 * @param url
 *            The URL to set up and receive content from
 * @return A valid HttpURLConnection
 * 
 * @throws IOException
 *             The openConnection() method throws an IOException and the calling method is responsible for handling it.
 */
public static HttpURLConnection openHttpConnection(URL url) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoInput(true);
    conn.setDoOutput(false);
    System.setProperty("http.agent", getUserAgent());
    conn.setRequestProperty("User-Agent", getUserAgent());
    HttpURLConnection.setFollowRedirects(true);
    conn.setUseCaches(false);
    conn.setInstanceFollowRedirects(true);
    return conn;
}

From source file:org.alfresco.mobile.android.api.network.NetworkHttpInvoker.java

private static Response invoke(UrlBuilder url, String method, String contentType,
        Map<String, List<String>> httpHeaders, Output writer, boolean forceOutput, BigInteger offset,
        BigInteger length, Map<String, String> params) {
    try {//  ww  w .ja  v a2  s.c o  m
        // Log.d("URL", url.toString());

        // connect
        HttpURLConnection conn = (HttpURLConnection) (new URL(url.toString())).openConnection();
        conn.setRequestMethod(method);
        conn.setDoInput(true);
        conn.setDoOutput(writer != null || forceOutput);
        conn.setAllowUserInteraction(false);
        conn.setUseCaches(false);
        conn.setRequestProperty("User-Agent", ClientVersion.OPENCMIS_CLIENT);

        // set content type
        if (contentType != null) {
            conn.setRequestProperty("Content-Type", contentType);
        }
        // set other headers
        if (httpHeaders != null) {
            for (Map.Entry<String, List<String>> header : httpHeaders.entrySet()) {
                if (header.getValue() != null) {
                    for (String value : header.getValue()) {
                        conn.addRequestProperty(header.getKey(), value);
                    }
                }
            }
        }

        // range
        BigInteger tmpOffset = offset;
        if ((tmpOffset != null) || (length != null)) {
            StringBuilder sb = new StringBuilder("bytes=");

            if ((tmpOffset == null) || (tmpOffset.signum() == -1)) {
                tmpOffset = BigInteger.ZERO;
            }

            sb.append(tmpOffset.toString());
            sb.append("-");

            if ((length != null) && (length.signum() == 1)) {
                sb.append(tmpOffset.add(length.subtract(BigInteger.ONE)).toString());
            }

            conn.setRequestProperty("Range", sb.toString());
        }

        conn.setRequestProperty("Accept-Encoding", "gzip,deflate");

        // add url form parameters
        if (params != null) {
            DataOutputStream ostream = null;
            OutputStream os = null;
            try {
                os = conn.getOutputStream();
                ostream = new DataOutputStream(os);

                Set<String> parameters = params.keySet();
                StringBuffer buf = new StringBuffer();

                int paramCount = 0;
                for (String it : parameters) {
                    String parameterName = it;
                    String parameterValue = (String) params.get(parameterName);

                    if (parameterValue != null) {
                        parameterValue = URLEncoder.encode(parameterValue, "UTF-8");
                        if (paramCount > 0) {
                            buf.append("&");
                        }
                        buf.append(parameterName);
                        buf.append("=");
                        buf.append(parameterValue);
                        ++paramCount;
                    }
                }
                ostream.writeBytes(buf.toString());
            } finally {
                if (ostream != null) {
                    ostream.flush();
                    ostream.close();
                }
                IOUtils.closeStream(os);
            }
        }

        // send data

        if (writer != null) {
            // conn.setChunkedStreamingMode((64 * 1024) - 1);
            OutputStream connOut = null;
            connOut = conn.getOutputStream();
            OutputStream out = new BufferedOutputStream(connOut, BUFFER_SIZE);
            writer.write(out);
            out.flush();
        }

        // connect
        conn.connect();

        // get stream, if present
        int respCode = conn.getResponseCode();
        InputStream inputStream = null;
        if ((respCode == HttpStatus.SC_OK) || (respCode == HttpStatus.SC_CREATED)
                || (respCode == HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION)
                || (respCode == HttpStatus.SC_PARTIAL_CONTENT)) {
            inputStream = conn.getInputStream();
        }

        // get the response
        return new Response(respCode, conn.getResponseMessage(), conn.getHeaderFields(), inputStream,
                conn.getErrorStream());
    } catch (Exception e) {
        throw new CmisConnectionException("Cannot access " + url + ": " + e.getMessage(), e);
    }
}

From source file:io.apiman.manager.test.es.ESMetricsAccessorTest.java

private static void loadTestData() throws Exception {
    String url = "http://localhost:6500/_bulk";
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestMethod("POST");
    conn.setDoInput(true);
    conn.setDoOutput(true);/*  www  .  jav a2  s  .com*/
    OutputStream os = conn.getOutputStream();
    InputStream is = ESMetricsAccessorTest.class.getResourceAsStream("bulk-metrics-data.txt");
    IOUtils.copy(is, os);
    IOUtils.closeQuietly(is);
    IOUtils.closeQuietly(os);
    if (conn.getResponseCode() > 299) {
        IOUtils.copy(conn.getInputStream(), System.err);
        throw new IOException("Bulk load of data failed with: " + conn.getResponseMessage());
    }

    client.execute(new Refresh.Builder().addIndex("apiman_metrics").refresh(true).build());
}

From source file:com.wx.kernel.util.HttpKit.java

private static HttpURLConnection getHttpConnection(String url, String method, Map<String, String> headers)
        throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
    URL _url = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) _url.openConnection();
    if (conn instanceof HttpsURLConnection) {
        ((HttpsURLConnection) conn).setSSLSocketFactory(sslSocketFactory);
        ((HttpsURLConnection) conn).setHostnameVerifier(trustAnyHostnameVerifier);
    }//  w w w  . j a  v  a  2 s . c  om

    conn.setRequestMethod(method);
    conn.setDoOutput(true);
    conn.setDoInput(true);

    conn.setConnectTimeout(19000);
    conn.setReadTimeout(19000);

    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("User-Agent",
            "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");

    if (headers != null && !headers.isEmpty())
        for (Entry<String, String> entry : headers.entrySet())
            conn.setRequestProperty(entry.getKey(), entry.getValue());

    return conn;
}

From source file:fr.zcraft.zlib.tools.mojang.UUIDFetcher.java

/**
 * Opens a POST connection.//from w w w. j  av  a  2s.c  o m
 *
 * @param url The URL to connect to.
 *
 * @return A POST connection to this URL.
 * @throws IOException If an exception occurred while contacting the server.
 */
static private HttpURLConnection getPOSTConnection(String url) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/json");
    connection.setUseCaches(false);
    connection.setDoInput(true);
    connection.setDoOutput(true);

    return connection;
}