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.external.volley.toolbox.HurlStack.java

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

    OkHttpClient okHttpClient = new OkHttpClient();
    HttpURLConnection connection = new OkUrlFactory(okHttpClient).open(url);

    int timeoutMs = request.getTimeoutMs();
    connection.setConnectTimeout(timeoutMs);
    connection.setReadTimeout(timeoutMs);
    connection.setUseCaches(false);
    connection.setDoInput(true);
    connection.setRequestProperty("Charset", "UTF-8"); // ?
    connection.setRequestProperty("connection", "keep-alive");

    // 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:com.hackerati.android.user_sdk.volley.HHurlStack.java

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

    final 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:eu.codeplumbers.cosi.api.tasks.RegisterDeviceTask.java

@Override
protected Device doInBackground(Void... voids) {
    URL urlO = null;//from   w w w  .j a  va2s . co  m
    try {
        urlO = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        OutputStream os = conn.getOutputStream();
        os.write(deviceString.getBytes("UTF-8"));
        os.flush();

        // read the response
        int status = conn.getResponseCode();
        InputStream in = null;

        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            in = conn.getErrorStream();
        } else {
            in = conn.getInputStream();
        }

        StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "UTF-8");
        String result = writer.toString();

        JSONObject jsonObject = new JSONObject(result);

        if (jsonObject != null) {
            if (jsonObject.has("login")) {
                resultDevice = new Device();
                resultDevice.setUrl(url.replace("/device/", ""));
                //Log.d(getClass().getName(), "Token="+jsonObject.getString("login"));
                resultDevice.setLogin(jsonObject.getString("login"));
                resultDevice.setPassword(jsonObject.getString("password"));
                resultDevice.setPermissions(jsonObject.getString("permissions"));

                resultDevice.setFirstSyncDone(false);
                resultDevice.setSyncCalls(false);
                resultDevice.setSyncContacts(false);
                resultDevice.setSyncFiles(false);
                resultDevice.setSyncNotes(false);

                resultDevice.save();
            } else {
                errorMessage = jsonObject.getString("error");
            }
        }

        in.close();
        conn.disconnect();

    } catch (MalformedURLException e) {
        errorMessage = e.getLocalizedMessage();
    } catch (ProtocolException e) {
        errorMessage = e.getLocalizedMessage();
    } catch (IOException e) {
        errorMessage = e.getLocalizedMessage();
    } catch (JSONException e) {
        errorMessage = e.getLocalizedMessage();
    }

    return resultDevice;
}

From source file:com.baasbox.android.HttpUrlConnectionClient.java

private HttpURLConnection openConnection(String urlString) throws BaasIOException, IOException {
    URL url = null;/*ww  w . j  a  va2s  .c om*/
    try {
        url = new URL(urlString);
    } catch (MalformedURLException e) {
        throw new BaasIOException("Error while parsing url " + urlString, e);
    }
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setConnectTimeout(config.httpConnectionTimeout);
    connection.setReadTimeout(config.httpSocketTimeout);
    connection.setInstanceFollowRedirects(true);
    connection.setDoInput(true);

    return connection;
}

From source file:com.app.milesoft.facebook.Util.java

/**
 * Connect to an HTTP URL and return the response as a string.
 *
 * 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//from w  ww  .  j a  v a 2s .c  om
 * @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);
    }
    Log.d("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.getByteArray(key) != null) {
                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.setRequestProperty("application/json","multipart/form-data;boundary="+strBoundary);
        conn.setDoOutput(true);
        conn.setDoInput(true);

        conn.setRequestProperty("Connection", "Keep-Alive");
        System.out.println("step 1");
        conn.connect();
        System.out.println("step 2");
        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:eu.codeplumbers.cosi.api.tasks.GetPlacesTask.java

@Override
protected List<Place> doInBackground(Void... voids) {
    URL urlO = null;//w ww.j  a va 2 s . co  m
    try {
        urlO = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        // read the response
        int status = conn.getResponseCode();
        InputStream in = null;

        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            in = conn.getErrorStream();
        } else {
            in = conn.getInputStream();
        }

        StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "UTF-8");
        String result = writer.toString();

        JSONArray jsonArray = new JSONArray(result);

        if (jsonArray != null) {
            if (jsonArray.length() > 0) {
                for (int i = 0; i < jsonArray.length(); i++) {
                    String version = "0";
                    if (jsonArray.getJSONObject(i).has("version")) {
                        version = jsonArray.getJSONObject(i).getString("version");
                    }
                    JSONObject placeJson = jsonArray.getJSONObject(i).getJSONObject("value");
                    Place place = Place.getByLocation(placeJson.get("description").toString(),
                            placeJson.get("latitude").toString(), placeJson.get("longitude").toString());

                    if (place == null) {
                        place = new Place(placeJson);
                    } else {
                        place.setDeviceId(placeJson.getString("deviceId"));
                        place.setAddress(placeJson.getString("address"));
                        place.setDateAndTime(placeJson.getString("dateAndTime"));
                        place.setLongitude(placeJson.getDouble("longitude"));
                        place.setLatitude(placeJson.getDouble("latitude"));
                        place.setRemoteId(placeJson.getString("_id"));
                    }

                    publishProgress("Saving place : " + place.getAddress());
                    place.save();

                    allPlaces.add(place);
                }
            } else {
                publishProgress("Your Cozy has no places stored.");
                return allPlaces;
            }
        } else {
            errorMessage = "Failed to parse API response";
        }

        in.close();
        conn.disconnect();

    } catch (MalformedURLException e) {
        e.printStackTrace();
        errorMessage = e.getLocalizedMessage();
    } catch (ProtocolException e) {
        errorMessage = e.getLocalizedMessage();
        e.printStackTrace();
    } catch (IOException e) {
        errorMessage = e.getLocalizedMessage();
        e.printStackTrace();
    } catch (JSONException e) {
        errorMessage = e.getLocalizedMessage();
        e.printStackTrace();
    }

    return allPlaces;
}

From source file:com.nxt.zyl.data.volley.toolbox.HurlStack.java

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

    int timeoutMs = request.getTimeoutMs();
    connection.setConnectTimeout(CONNECTION_TIME_OUT_MS);
    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:com.atinternet.tracker.TVTrackingPlugin.java

@Override
protected void execute(Tracker tracker) {
    this.tracker = tracker;
    try {//  w w w  .ja v a 2s  .c o  m
        if (sessionIsExpired()) {
            setDirectCampaignToRemanent();

            URL url = new URL(tracker.TVTracking().getCampaignURL());
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setReadTimeout(TIMEOUT);
            connection.setConnectTimeout(TIMEOUT);
            connection.setDoInput(true);
            connection.connect();
            response = getTvTrackingResponse(stringifyTvTResponse(connection), connection);
            connection.disconnect();
        } else {
            response = getTvTrackingResponse(
                    Tracker.getPreferences().getString(TrackerConfigurationKeys.DIRECT_CAMPAIGN_SAVED, null),
                    null);
        }
        Tool.executeCallback(tracker.getListener(), Tool.CallbackType.partner, "TV Tracking : " + response);
        Tracker.getPreferences().edit()
                .putLong(TrackerConfigurationKeys.LAST_TVT_EXECUTE_TIME, System.currentTimeMillis()).apply();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.attask.api.StreamClient.java

private HttpURLConnection createConnection(String spec, String method) throws IOException {
    URL url = new URL(spec);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    if (conn instanceof HttpsURLConnection) {
        ((HttpsURLConnection) conn).setHostnameVerifier(HOSTNAME_VERIFIER);
    }/*from   ww  w.j a va2  s  .co  m*/

    conn.setAllowUserInteraction(false);
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setConnectTimeout(60000);
    conn.setReadTimeout(300000);
    conn.connect();

    return conn;
}

From source file:it.greenvulcano.gvesb.adapter.http.mapping.ForwardHttpServletMapping.java

@SuppressWarnings("deprecation")
@Override/*from   ww w  . j  av  a 2s  .c  o  m*/
public void handleRequest(String methodName, HttpServletRequest req, HttpServletResponse resp)
        throws InboundHttpResponseException {

    logger.debug("BEGIN forward: " + req.getRequestURI());

    final HttpURLConnection httpConnection = (HttpURLConnection) connection;
    ;

    try {

        httpConnection.setRequestMethod(methodName);
        httpConnection.setReadTimeout(soTimeout);
        httpConnection.setDoInput(true);
        httpConnection.setDoOutput(true);

        if (dump) {
            StringBuffer sb = new StringBuffer();
            DumpUtils.dump(req, sb);
            logger.info(sb.toString());
        }

        String mapping = req.getPathInfo();
        if (mapping == null) {
            mapping = "/";
        }
        String destPath = contextPath + mapping;
        String queryString = req.getQueryString();
        if (queryString != null) {
            destPath += "?" + queryString;
        }
        if (!destPath.startsWith("/")) {
            destPath = "/" + destPath;
        }
        logger.info("Resulting QueryString: " + destPath);

        Collections.list(req.getHeaderNames()).forEach(headerName -> {
            httpConnection.setRequestProperty(headerName,
                    Collections.list(req.getHeaders(headerName)).stream().collect(Collectors.joining(";")));
        });

        if (methodName.equalsIgnoreCase("POST") || methodName.equalsIgnoreCase("PUT")) {
            httpConnection.setDoOutput(true);
            IOUtils.copy(req.getInputStream(), httpConnection.getOutputStream());

        }

        httpConnection.connect();
        int status = httpConnection.getResponseCode();

        resp.setStatus(status, httpConnection.getResponseMessage());

        httpConnection.getHeaderFields().entrySet().stream().forEach(header -> {
            resp.addHeader(header.getKey(), header.getValue().stream().collect(Collectors.joining(";")));
        });

        ByteArrayOutputStream bodyOut = new ByteArrayOutputStream();
        IOUtils.copy(httpConnection.getInputStream(), bodyOut);

        OutputStream out = resp.getOutputStream();
        out.write(bodyOut.toByteArray());
        //IOUtils.copy(method.getResponseBodyAsStream(), out);
        out.flush();
        out.close();

        if (dump) {
            StringBuffer sb = new StringBuffer();
            DumpUtils.dump(resp, bodyOut, sb);
            logger.info(sb.toString());
        }

    } catch (Exception exc) {
        logger.error("ERROR on forwarding: " + req.getRequestURI(), exc);
        throw new InboundHttpResponseException("GV_CALL_SERVICE_ERROR",
                new String[][] { { "message", exc.getMessage() } }, exc);
    } finally {
        try {
            if (httpConnection != null) {
                httpConnection.disconnect();
            }
        } catch (Exception exc) {
            logger.warn("Error while releasing connection", exc);
        }
        logger.debug("END forward: " + req.getRequestURI());
    }
}