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

/**
 * Send the POST request to the Wikitude Cloud Targets API.
 * //from  w  w w.j  av  a 2  s .  c o m
 * <b>Remark</b>: We are not using any external libraries for sending HTTP
 * requests, to be as independent as possible. Libraries like Apache
 * HttpComponents (included in Android already) make it a lot easier to
 * interact with HTTP connections.
 * 
 * @param body
 *            The JSON body that is sent in the request.
 * @return The response from the server, in JSON format
 * 
 * @throws IOException
 *             when the server cannot serve the request for any reason, or
 *             anything went wrong during the communication between client
 *             and server.
 * 
 */
private String sendRequest(String body) throws IOException {

    BufferedReader reader = null;
    OutputStreamWriter writer = null;

    try {

        // create the URL object from the endpoint
        URL url = new URL(API_ENDPOINT);

        // open the connection
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // use POST and configure the connection
        connection.setRequestMethod("POST");
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);

        // set the request headers
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("X-Api-Token", apiToken);
        connection.setRequestProperty("X-Version", "" + apiVersion);
        connection.setRequestProperty("Content-Length", String.valueOf(body.length()));

        // construct the writer and write request
        writer = new OutputStreamWriter(connection.getOutputStream());
        writer.write(body);
        writer.flush();

        // listen on the server response
        reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

        // construct the server response and return
        StringBuilder sb = new StringBuilder();
        for (String line; (line = reader.readLine()) != null;) {
            sb.append(line);
        }

        // return the result
        return sb.toString();

    } catch (MalformedURLException e) {
        // the URL we specified as endpoint was not valid
        System.err.println("The URL " + API_ENDPOINT + " is not a valid URL");
        e.printStackTrace();
        return null;
    } catch (ProtocolException e) {
        // this should not happen, it means that we specified a wrong
        // protocol
        System.err.println("The HTTP method is not valid. Please check if you specified POST.");
        e.printStackTrace();
        return null;
    } finally {
        // close the reader and writer
        try {
            writer.close();
        } catch (Exception e) {
            // intentionally left blank
        }
        try {
            reader.close();
        } catch (Exception e) {
            // intentionally left blank
        }
    }
}

From source file:org.mf.api.net.stack.HurlStack.java

/**
 * Opens an {@link HttpURLConnection} with parameters.
 * @return an open connection//ww w. java  2s  . com
 */
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);
    connection.setChunkedStreamingMode(0);

    // 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:it.acubelab.batframework.systemPlugins.TagmeAnnotator.java

@Override
public HashSet<ScoredAnnotation> solveSa2W(String text) throws AnnotationException {
    // System.out.println(text.length()+ " "+text.substring(0,
    // Math.min(text.length(), 15)));
    // TODO: workaround for a bug in tagme. should be deleted afterwards.
    String newText = "";
    for (int i = 0; i < text.length(); i++)
        newText += (text.charAt(i) > 127 ? ' ' : text.charAt(i));
    text = newText;//from  ww  w.j a  va 2s .c o m

    // avoid crashes for empty documents
    int j = 0;
    while (j < text.length() && text.charAt(j) == ' ')
        j++;
    if (j == text.length())
        return new HashSet<ScoredAnnotation>();

    HashSet<ScoredAnnotation> res;
    String params = null;
    try {
        res = new HashSet<ScoredAnnotation>();

        params = "key=" + this.key;
        params += "&lang=en";
        if (epsilon >= 0)
            params += "&epsilon=" + epsilon;
        if (minComm >= 0)
            params += "&min_comm=" + minComm;
        if (minLink >= 0)
            params += "&min_link=" + minLink;
        params += "&text=" + URLEncoder.encode(text, "UTF-8");
        URL wikiApi = new URL(url);

        HttpURLConnection slConnection = (HttpURLConnection) wikiApi.openConnection();
        slConnection.setRequestProperty("accept", "text/xml");
        slConnection.setDoOutput(true);
        slConnection.setDoInput(true);
        slConnection.setRequestMethod("POST");
        slConnection.setRequestProperty("charset", "utf-8");
        slConnection.setRequestProperty("Content-Length", Integer.toString(params.getBytes().length));
        slConnection.setUseCaches(false);
        slConnection.setReadTimeout(0);

        DataOutputStream wr = new DataOutputStream(slConnection.getOutputStream());
        wr.writeBytes(params);
        wr.flush();
        wr.close();

        Scanner s = new Scanner(slConnection.getInputStream());
        Scanner s2 = s.useDelimiter("\\A");
        String resultStr = s2.hasNext() ? s2.next() : "";
        s.close();

        JSONObject obj = (JSONObject) JSONValue.parse(resultStr);
        lastTime = (Long) obj.get("time");

        JSONArray jsAnnotations = (JSONArray) obj.get("annotations");
        for (Object js_ann_obj : jsAnnotations) {
            JSONObject js_ann = (JSONObject) js_ann_obj;
            System.out.println(js_ann);
            int start = ((Long) js_ann.get("start")).intValue();
            int end = ((Long) js_ann.get("end")).intValue();
            int id = ((Long) js_ann.get("id")).intValue();
            float rho = Float.parseFloat((String) js_ann.get("rho"));
            System.out.println(text.substring(start, end) + "->" + id + " (" + rho + ")");
            res.add(new ScoredAnnotation(start, end - start, id, (float) rho));
        }

    } catch (Exception e) {
        e.printStackTrace();
        throw new AnnotationException("An error occurred while querying TagMe API. Message: " + e.getMessage()
                + " Parameters:" + params);
    }
    return res;

}

From source file:com.facebook.android.library.Util.java

/**
 * Connect to an HTTP URL and return the response as a string.
 * /*  w  ww. j  av  a  2s .co m*/
 * Note that the HTTP method override is used on non-GET requests. (i.e.
 * requests are made as "POST" with method specified in the body).
 * 
 * @param url
 *            - the resource to open: must be a welformed URL
 * @param method
 *            - the HTTP method to use ("GET", "POST", etc.)
 * @param params
 *            - the query parameter for the URL (e.g. access_token=foo)
 * @return the URL contents as a String
 * @throws MalformedURLException
 *             - if the URL format is invalid
 * @throws IOException
 *             - if a network problem occurs
 */
public static String openUrl(String url, String method, Bundle params)
        throws MalformedURLException, IOException {
    // random string as boundary for multi-part http post
    String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
    String endLine = "\r\n";

    OutputStream os;

    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }
    Util.logd("Facebook-Util", method + " URL: " + url);
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK");
    if (!method.equals("GET")) {
        Bundle dataparams = new Bundle();
        for (String key : params.keySet()) {
            if (params.get(key) instanceof byte[]) {
                dataparams.putByteArray(key, params.getByteArray(key));
            }

        }

        // use method override
        if (!params.containsKey("method")) {
            params.putString("method", method);
        }

        if (params.containsKey("access_token")) {
            String decoded_token = URLDecoder.decode(params.getString("access_token"));
            params.putString("access_token", decoded_token);
        }

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.connect();
        os = new BufferedOutputStream(conn.getOutputStream());

        os.write(("--" + strBoundary + endLine).getBytes());
        os.write((encodePostBody(params, strBoundary)).getBytes());
        os.write((endLine + "--" + strBoundary + endLine).getBytes());

        if (!dataparams.isEmpty()) {

            for (String key : dataparams.keySet()) {
                os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes());
                os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes());
                os.write(dataparams.getByteArray(key));
                os.write((endLine + "--" + strBoundary + endLine).getBytes());

            }
        }
        os.flush();
    }

    String response = "";
    try {
        response = read(conn.getInputStream());
    } catch (FileNotFoundException e) {
        // Error Stream contains JSON that we can parse to a FB error
        response = read(conn.getErrorStream());
    }
    return response;
}

From source file:com.anyonavinfo.commonuserregister.MainActivity.java

/**
 * Post?/*from ww w.ja va 2s  .  c  o  m*/
 */
public static String doPost(String urlStr, File file) {
    URL url = null;
    HttpURLConnection conn = null;
    InputStream is = null;
    ByteArrayOutputStream baos = null;
    String BOUNDARY = UUID.randomUUID().toString(); //  ??
    String PREFIX = "--", LINE_END = "\r\n";
    String CONTENT_TYPE = "multipart/form-data"; // 

    try {
        url = new URL(urlStr);
        conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(15000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("POST");
        conn.setDoInput(true); // ??
        conn.setDoOutput(true); // ??
        conn.setUseCaches(false); // ??
        conn.setRequestProperty("encoding", "utf-8");
        conn.setRequestProperty("connection", "keep-alive");
        conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);

        if (file != null) {
            /**
             * ?
             */
            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
            StringBuffer sb = new StringBuffer();
            sb.append(PREFIX);
            sb.append(BOUNDARY);
            sb.append(LINE_END);
            /**
             * ?? name???key ?key ??
             * filename??????
             */

            sb.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\""
                    + LINE_END);
            sb.append("Content-Type: application/octet-stream; charset=" + "utf-8" + LINE_END);
            sb.append(LINE_END);
            dos.write(sb.toString().getBytes());
            InputStream IS = new FileInputStream(file);
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = IS.read(bytes)) != -1) {
                dos.write(bytes, 0, len);
            }
            IS.close();
            dos.write(LINE_END.getBytes());
            byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
            dos.write(end_data);
            dos.flush();
        }

        if (conn.getResponseCode() == 200) {
            is = conn.getInputStream();
            baos = new ByteArrayOutputStream();
            int len = -1;
            byte[] buf = new byte[128];

            while ((len = is.read(buf)) != -1) {
                baos.write(buf, 0, len);
                Log.d("Sjj--->", len + "");
            }
            baos.flush();
            return baos.toString();
        } else {
            throw new RuntimeException(" responseCode is not 200 ... ");
        }

    } catch (Exception e) {
        // 
        if (e instanceof SocketTimeoutException) {
            return "SocketTimeoutException";
        } else if (e instanceof UnknownHostException) {
            return "UnknownHostException";
        }
        e.printStackTrace();
    } finally {
        try {
            if (is != null)
                is.close();
            if (baos != null)
                baos.close();
            if (conn != null) {
                conn.disconnect();
            }
        } catch (IOException e) {
        }
    }

    return null;
}

From source file:de.thingweb.discovery.TDRepository.java

/** This method takes a free text search and send it o the TD repository 
 * @param search free text search/*w  w  w  .  j a v  a  2s  .c  o m*/
 * @return JSONObject of relevant TD files (=empty array means no match)
 * @throws Exception error
 * */
public JSONObject tdFreeTextSearch(String search) throws Exception {

    search = URLEncoder.encode("?s <http://www.w3c.org/wot/td#name> \"" + search + "\"", "UTF-8");

    URL myURL = new URL("http://" + repository_uri + "/td?query=" + search);
    HttpURLConnection myURLConnection = (HttpURLConnection) myURL.openConnection();
    myURLConnection.setRequestMethod("GET");
    myURLConnection.setRequestProperty("Content-Type", "application/ld+json");
    myURLConnection.setDoInput(true);
    myURLConnection.setDoOutput(true);

    InputStream in = myURLConnection.getInputStream();

    //   JSONArray jsonLDs = new JSONArray(streamToString(in));

    JSONObject jsonLDs = new JSONObject(streamToString(in));

    System.out.println(jsonLDs);

    return jsonLDs;
}

From source file:com.google.android.apps.santatracker.service.RemoteApiProcessor.java

/**
 * Downloads the given URL and return//  ww  w.j  a v a  2s .c o m
 */
protected String downloadUrl(String myurl) throws IOException {
    InputStream is = null;
    // Only display the first 500 characters of the retrieved
    // web page content.
    // int len = 500;

    try {
        URL url = new URL(myurl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        // Starts the query
        conn.connect();
        int response = conn.getResponseCode();
        if (!isValidHeader(conn)) {
            // not a valid header
            Log.d(TAG, "Santa communication failure.");
            return null;

        } else if (response != 200) {
            Log.d(TAG, "Santa communication failure " + response);
            return null;

        } else {
            is = conn.getInputStream();

            // Convert the InputStream into a string
            return read(is).toString();
        }

        // Makes sure that the InputStream is closed
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:de.thingweb.discovery.TDRepository.java

/**  This method takes a SPARQL query and send it o the TD repository    
 * @param search SPARQL query//from  www .  j av  a 2  s. c  o  m
 * @return JSONObject array of relevant TD files (=empty array means no match)
 * @throws Exception error
 * */
public JSONObject tdTripleSearch(String search) throws Exception {

    // if triple search contains spaces, replaces with  %20
    //String search_without_space = search.replace(" ", " %20");
    search = URLEncoder.encode(search, "UTF-8");

    URL myURL = new URL("http://" + repository_uri + "/td?query=" + search);
    HttpURLConnection myURLConnection = (HttpURLConnection) myURL.openConnection();
    myURLConnection.setRequestMethod("GET");
    myURLConnection.setRequestProperty("Content-Type", "application/ld+json");
    myURLConnection.setDoInput(true);
    myURLConnection.setDoOutput(true);

    InputStream in = myURLConnection.getInputStream();

    //   JSONArray jsonLDs = new JSONArray(streamToString(in));

    JSONObject jsonLDs = new JSONObject(streamToString(in));

    System.out.println(jsonLDs);

    return jsonLDs;
}

From source file:ch.pec0ra.mobilityratecalculator.DistanceCalculator.java

private String downloadUrl(String myurl) throws IOException {
    InputStream is = null;/*from  w  w w. j  a v a 2s .c  om*/

    try {
        URL url = new URL(myurl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        // Starts the query
        conn.connect();
        conn.getResponseCode();
        is = conn.getInputStream();

        String responseAsString = CharStreams.toString(new InputStreamReader(is));
        return responseAsString;

        // Makes sure that the InputStream is closed after the app is
        // finished using it.
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:com.epam.catgenome.manager.externaldb.HttpDataManager.java

private String getResultFromURL(final String location) throws ExternalDbUnavailableException {

    HttpURLConnection conn = null;
    try {/*from   w  w w  . j av  a2 s. c  om*/
        conn = createConnection(location);
        HttpURLConnection.setFollowRedirects(true);
        conn.setDoInput(true);
        conn.setRequestProperty(CONTENT_TYPE, APPLICATION_JSON);
        conn.connect();

        int status = conn.getResponseCode();

        while (true) {
            long wait = 0;
            String header = conn.getHeaderField(HTTP_HEADER_RETRY_AFTER);

            if (header != null) {
                wait = Integer.valueOf(header);
            }

            if (wait == 0) {
                break;
            }

            LOGGER.info(String.format(WAITING_FORMAT, wait));
            conn.disconnect();

            Thread.sleep(wait * MILLIS_IN_SECOND);

            conn = (HttpURLConnection) new URL(location).openConnection();
            conn.setDoInput(true);
            conn.connect();
            status = conn.getResponseCode();

        }
        return getHttpResult(status, location, conn);
    } catch (InterruptedException | IOException e) {
        throw new ExternalDbUnavailableException(String.format(EXCEPTION_MESSAGE, location), e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }

        resetProxy();
    }
}