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:export.Facebook.java

private JSONObject createRun(JSONObject ref, JSONObject runObj) throws Exception {
    int sport = runObj.optInt("sport", DB.ACTIVITY.SPORT_OTHER);
    if (sport != DB.ACTIVITY.SPORT_RUNNING && sport != DB.ACTIVITY.SPORT_BIKING) {

        /* only running and biking is supported */
        return null;
    }//from  w w w  .ja  v  a2  s . com
    String id = ref.getString("id");
    ArrayList<Part<?>> list = new ArrayList<Part<?>>();
    list.add(new Part<StringWritable>("access_token", new StringWritable(FormCrawler.URLEncode(access_token))));
    list.add(new Part<StringWritable>("course", new StringWritable(id)));
    if (explicitly_shared)
        list.add(new Part<StringWritable>("fb:explicitly_shared", new StringWritable("true")));

    list.add(new Part<StringWritable>("start_time",
            new StringWritable(formatTime(runObj.getLong("startTime")))));
    if (runObj.has("endTime")) {
        list.add(new Part<StringWritable>("end_time",
                new StringWritable(formatTime(runObj.getLong("endTime")))));
    }

    if (uploadComment && runObj.has("comment")) {
        list.add(new Part<StringWritable>("message", new StringWritable(runObj.getString("comment"))));
    }

    Part<?> parts[] = new Part<?>[list.size()];
    list.toArray(parts);

    URL url = new URL(sport == DB.ACTIVITY.SPORT_RUNNING ? RUN_ENDPOINT : BIKE_ENDPOINT);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestMethod("POST");
    postMulti(conn, parts);

    int code = conn.getResponseCode();
    String msg = conn.getResponseMessage();

    InputStream in = new BufferedInputStream(conn.getInputStream());
    JSONObject runRef = parse(in);

    conn.disconnect();
    if (code != 200) {
        throw new Exception("Got code: " + code + ", msg: " + msg + " from " + url.toString());
    }

    return runRef;
}

From source file:TaxSvc.TaxSvc.java

public GetTaxResult GetTax(GetTaxRequest req) {

    //Create URL/*  ww  w . ja v a  2s. c  o m*/
    String taxget = svcURL + "/1.0/tax/get";
    URL url;

    HttpURLConnection conn;
    try {
        //Connect to URL with authorization header, request content.
        url = new URL(taxget);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);

        String encoded = "Basic " + new String(Base64.encodeBase64((accountNum + ":" + license).getBytes())); //Create auth content
        conn.setRequestProperty("Authorization", encoded); //Add authorization header
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(Include.NON_NULL); //Tells the serializer to only include those parameters that are not null
        String content = mapper.writeValueAsString(req);
        //System.out.println(content);   //Uncomment to see the content of the request object
        conn.setRequestProperty("Content-Length", Integer.toString(content.length()));

        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(content);
        wr.flush();
        wr.close();

        conn.disconnect();

        if (conn.getResponseCode() != 200) //If we didn't get a success back, print out the error.
        {
            GetTaxResult res = mapper.readValue(conn.getErrorStream(), GetTaxResult.class); //Deserializes the response
            return res;
        }

        else //Otherwise, print out the total tax calculated
        {
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            GetTaxResult res = mapper.readValue(conn.getInputStream(), GetTaxResult.class); //Deserializes the response
            return res;
        }

    } catch (IOException e) {
        e.printStackTrace();
        return null;

    }
}

From source file:com.github.bmadecoder.Authenticator.java

public long getTimeDiff() {
    if (!this.syncing) {
        return 0;
    }//from  www  . j  av  a2 s  . c  om
    try {
        URL url = URI.create("http://m.eu.mobileservice.blizzard.com/enrollment/time.htm").toURL();
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-type", "application/octet-stream");
        conn.setRequestProperty("Accept", "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2");
        conn.setReadTimeout(10000);
        conn.setDoInput(true);
        conn.connect();

        byte[] servertime = new byte[8];
        InputStream connectionStream = conn.getInputStream();
        connectionStream.read(servertime, 0, 8);
        connectionStream.close();
        conn.disconnect();

        return new BigInteger(servertime).longValue() - System.currentTimeMillis();
    } catch (MalformedURLException e) {
        throw new IllegalStateException(e);
    } catch (IOException e) {
        return 0;
    }
}

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

/**
 * Opens an {@link HttpURLConnection} with parameters.
 * @param url//from w w w  .ja v  a 2 s .c o m
 * @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:com.jeffrodriguez.webtools.client.URLConnectionWebClientImpl.java

@Override
public Map<String, List<String>> getHeaders(String url) throws IOException {

    logger.log(Level.INFO, "Getting HEAD from {0}", url);

    // Build and connect
    HttpURLConnection connection = buildConnection(url);
    connection.setDoInput(true);
    connection.setRequestMethod("HEAD");
    connection.connect();//w w w .java 2  s . co  m

    // Get the headers
    return disconnectAndReturn(connection, connection.getHeaderFields());
}

From source file:export.Facebook.java

private JSONObject createCourse(JSONObject course) throws JSONException, IOException, Exception {
    JSONObject obj = new JSONObject();
    /* create a facebook course instance */
    obj.put("fb:app_id", Facebook.CLIENT_ID);
    obj.put("og:type", "fitness.course");
    obj.put("og:title", "a RunnerUp course");
    obj.put("fitness", course);

    Part<StringWritable> themePart = new Part<StringWritable>("access_token",
            new StringWritable(FormCrawler.URLEncode(access_token)));
    Part<StringWritable> payloadPart = new Part<StringWritable>("object", new StringWritable(obj.toString()));
    Part<?> parts[] = { themePart, payloadPart };

    HttpURLConnection conn = (HttpURLConnection) new URL(COURSE_ENDPOINT).openConnection();
    conn.setDoOutput(true);// w ww.j  a va2  s . c om
    conn.setDoInput(true);
    conn.setRequestMethod("POST");
    postMulti(conn, parts);

    int code = conn.getResponseCode();
    String msg = conn.getResponseMessage();

    InputStream in = new BufferedInputStream(conn.getInputStream());
    JSONObject ref = parse(in);

    conn.disconnect();
    if (code != 200) {
        throw new Exception("got " + code + ": >" + msg + "< from createCourse");
    }

    return ref;
}

From source file:com.mabi87.httprequestbuilder.HTTPRequest.java

/**
 * @throws IOException//ww w .  j a v a2s  . co  m
 *             throws from HttpURLConnection method.
 * @return the HTTPResponse object
 */
private HTTPResponse get() throws IOException {
    URL url = null;

    if (mParameters.size() > 0) {
        url = new URL(mPath + "?" + getQuery(mParameters));
    } else {
        url = new URL(mPath);
    }

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

    lConnection.setReadTimeout(mReadTimeoutMillis);
    lConnection.setConnectTimeout(mConnectTimeoutMillis);
    lConnection.setRequestMethod("GET");
    lConnection.setDoInput(true);

    HTTPResponse response = readPage(lConnection);

    return response;
}

From source file:com.streamsets.datacollector.updatechecker.UpdateChecker.java

@Override
public void run() {
    updateInfo = null;/*w  w w  .  jav  a 2  s .  c  o  m*/
    PipelineState ps;
    try {
        ps = runner.getState();
    } catch (PipelineStoreException e) {
        LOG.warn(Utils.format("Cannot get pipeline state: '{}'", e.toString()), e);
        return;
    }
    if (ps.getStatus() == PipelineStatus.RUNNING) {
        if (url != null) {
            Map uploadInfo = getUploadInfo();
            if (uploadInfo != null) {
                HttpURLConnection conn = null;
                try {
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(2000);
                    conn.setReadTimeout(2000);
                    conn.setDoOutput(true);
                    conn.setDoInput(true);
                    conn.setRequestProperty("content-type", APPLICATION_JSON_MIME);
                    ObjectMapperFactory.getOneLine().writeValue(conn.getOutputStream(), uploadInfo);
                    if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                        String responseContentType = conn.getHeaderField("content-type");
                        if (APPLICATION_JSON_MIME.equals(responseContentType)) {
                            updateInfo = ObjectMapperFactory.get().readValue(conn.getInputStream(), Map.class);
                        } else {
                            LOG.trace("Got invalid content-type '{}' from from update-check server",
                                    responseContentType);
                        }
                    } else {
                        LOG.trace("Got '{} : {}' from update-check server", conn.getResponseCode(),
                                conn.getResponseMessage());
                    }
                } catch (Exception ex) {
                    LOG.trace("Could not do an update check: {}", ex.toString(), ex);
                } finally {
                    if (conn != null) {
                        conn.disconnect();
                    }
                }
            }
        }
    }
}

From source file:lk.appzone.client.MchoiceAventuraSmsSender.java

public String excutePost(String targetURL, String username, String password, String urlParameters)
        throws MchoiceAventuraMessagingException {
    URL url;//from   w  w w . j av  a 2s .c o  m
    HttpURLConnection connection = null;
    try {
        //Create connection
        url = new URL(targetURL);
        connection = (HttpURLConnection) url.openConnection();

        setSdpHeaderParams(connection);
        setBasicAuthentication(username, password, connection);

        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        sendRequest(urlParameters, connection);

        return getResponse(connection);

    } catch (Exception e) {
        logger.error("Error occcured while sending the request", e);
        throw new MchoiceAventuraMessagingException("Error occcured while sending the request", e);

    } finally {

        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:com.mabi87.httprequestbuilder.HTTPRequest.java

/**
 * @throws IOException/*from  w ww  .ja  v  a  2s.  c o  m*/
 *             throws from HttpURLConnection method.
 * @return the HTTPResponse object
 */
private HTTPResponse post() throws IOException {
    URL url = new URL(mPath);
    HttpURLConnection lConnection = (HttpURLConnection) url.openConnection();

    lConnection.setReadTimeout(mReadTimeoutMillis);
    lConnection.setConnectTimeout(mConnectTimeoutMillis);
    lConnection.setRequestMethod("POST");
    lConnection.setDoInput(true);
    lConnection.setDoOutput(true);

    OutputStream lOutStream = lConnection.getOutputStream();
    BufferedWriter lWriter = new BufferedWriter(new OutputStreamWriter(lOutStream, "UTF-8"));
    lWriter.write(getQuery(mParameters));
    lWriter.flush();
    lWriter.close();
    lOutStream.close();

    HTTPResponse response = readPage(lConnection);

    return response;
}