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:net.bashtech.geobot.BotManager.java

public static String postRemoteDataStrawpoll(String urlString) {

    String line = "";
    try {//from w w  w  . ja v  a  2  s .  c  om
        HttpURLConnection c = (HttpURLConnection) (new URL("http://strawpoll.me/api/v2/polls")
                .openConnection());

        c.setRequestMethod("POST");
        c.setRequestProperty("Content-Type", "application/json");
        c.setRequestProperty("User-Agent", "CB2");

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

        String queryString = urlString;

        c.setRequestProperty("Content-Length", Integer.toString(queryString.length()));

        DataOutputStream wr = new DataOutputStream(c.getOutputStream());
        wr.writeBytes(queryString);

        wr.flush();
        wr.close();

        Scanner inStream = new Scanner(c.getInputStream());

        while (inStream.hasNextLine())
            line += (inStream.nextLine());

        inStream.close();
        System.out.println(line);
        try {
            JSONParser parser = new JSONParser();
            Object obj = parser.parse(line);
            JSONObject jsonObject = (JSONObject) obj;
            line = (Long) jsonObject.get("id") + "";

        } catch (Exception e) {
            e.printStackTrace();
        }

    } catch (MalformedURLException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    return line;
}

From source file:com.mobile.godot.core.service.task.GodotAction.java

@Override
public void run() {

    System.out.println("inside runnable");

    android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);

    URL url = GodotURLUtils.parseToURL(this.mServlet, this.mParams);

    System.out.println("url: " + url);

    HttpURLConnection connection = null;
    InputStream iStream;/*from w  w w . j a  v a2s.  c o m*/
    InputStream eStream;
    int responseCode = 0;
    String data = null;

    try {

        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.connect();

        if (!url.getHost().equals(connection.getURL().getHost())) {
            this.mHandler.obtainMessage(GodotMessage.Error.REDIRECTION_ERROR).sendToTarget();
            connection.disconnect();
            return;
        }

        try {

            iStream = new BufferedInputStream(connection.getInputStream());
            BufferedReader bReader = new BufferedReader(new InputStreamReader(iStream));
            data = bReader.readLine();
            responseCode = connection.getResponseCode();

        } catch (IOException exc) {

            eStream = new BufferedInputStream(connection.getErrorStream());
            BufferedReader bReader = new BufferedReader(new InputStreamReader(eStream));
            data = bReader.readLine();
            responseCode = connection.getResponseCode();

        } finally {

            if (data != null) {

                this.mHandler.obtainMessage(this.mMessageMap.get(responseCode), data).sendToTarget();

            } else {

                this.mHandler.obtainMessage(this.mMessageMap.get(responseCode)).sendToTarget();

            }
        }

    } catch (IOException exc) {

        this.mHandler.obtainMessage(GodotMessage.Error.SERVER_ERROR).sendToTarget();

    } finally {

        connection.disconnect();

    }

}

From source file:edu.auburn.ppl.cyclecolumbus.NoteUploader.java

/******************************************************************************************
 * Uploads the note to the server/*from   ww  w.  ja  v a  2  s .  c o  m*/
 ******************************************************************************************
 * @param currentNoteId Unique note ID to be uploaded
 * @return True if uploaded, false if not
 ******************************************************************************************/
boolean uploadOneNote(long currentNoteId) {
    boolean result = false;
    final String postUrl = "http://FountainCityCycling.org/post/";

    try {

        URL url = new URL(postUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true); // Allow Inputs
        conn.setDoOutput(true); // Allow Outputs
        conn.setUseCaches(false); // Don't use a Cached Copy
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("ENCTYPE", "multipart/form-data");
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        conn.setRequestProperty("Cycleatl-Protocol-Version", "4");

        /*
        Change protocol to 2 for Note, and change the point where you zip up the body.  (Dont zip up trip body)
        Since notes don't work either, this may not solve it.
         */

        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

        JSONObject note = getNoteJSON(currentNoteId);
        deviceId = getDeviceId();

        dos.writeBytes("--cycle*******notedata*******columbus\r\n"
                + "Content-Disposition: form-data; name=\"note\"\r\n\r\n" + note.toString() + "\r\n");
        dos.writeBytes("--cycle*******notedata*******columbus\r\n"
                + "Content-Disposition: form-data; name=\"version\"\r\n\r\n"
                + String.valueOf(kSaveNoteProtocolVersion) + "\r\n");
        dos.writeBytes("--cycle*******notedata*******columbus\r\n"
                + "Content-Disposition: form-data; name=\"device\"\r\n\r\n" + deviceId + "\r\n");

        if (imageDataNull == false) {
            dos.writeBytes("--cycle*******notedata*******columbus\r\n"
                    + "Content-Disposition: form-data; name=\"file\"; filename=\"" + deviceId + ".jpg\"\r\n"
                    + "Content-Type: image/jpeg\r\n\r\n");
            dos.write(imageData);
            dos.writeBytes("\r\n");
        }

        dos.writeBytes("--cycle*******notedata*******columbus--\r\n");

        dos.flush();
        dos.close();

        int serverResponseCode = conn.getResponseCode();
        String serverResponseMessage = conn.getResponseMessage();
        // JSONObject responseData = new JSONObject(serverResponseMessage);
        Log.v("KENNY", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
        responseMessage = serverResponseMessage;
        responseCode = serverResponseCode;

        // 200 - 202 means successfully went to server and uploaded
        if (serverResponseCode == 200 || serverResponseCode == 201 || serverResponseCode == 202) {
            mDb.open();
            mDb.updateNoteStatus(currentNoteId, NoteData.STATUS_SENT);
            mDb.close();
            result = true;
        }
    } catch (IllegalStateException e) {
        Log.d("KENNY", "Note Catch: Illegal State Exception: " + e);
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        Log.d("KENNY", "Note Catch: IOException: " + e);
        e.printStackTrace();
        return false;
    } catch (JSONException e) {
        Log.d("KENNY", "Note Catch: JSONException: " + e);
        e.printStackTrace();
        return false;
    }
    return result;
}

From source file:com.scut.easyfe.network.kjFrame.http.HttpConnectStack.java

private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    int timeoutMs = request.getTimeoutMs();
    connection.setConnectTimeout(timeoutMs);
    connection.setReadTimeout(timeoutMs);
    connection.setUseCaches(false);// w ww. j a va2 s  .  co  m
    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:org.freshrss.easyrss.network.NetworkClient.java

public InputStream doPostStream(final String url, final String params) throws IOException, NetworkException {
    final HttpURLConnection conn = makeConnection(url);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    if (auth != null) {
        conn.setRequestProperty("Authorization", "GoogleLogin auth=" + auth);
    }//from   ww w .  j  av a  2s .  c  o  m
    conn.setDoInput(true);
    conn.setDoOutput(true);
    final OutputStream output = conn.getOutputStream();
    output.write(params.getBytes());
    output.flush();
    output.close();

    conn.connect();
    try {
        final int resStatus = conn.getResponseCode();
        if (resStatus == HttpStatus.SC_UNAUTHORIZED) {
            ReaderAccountMgr.getInstance().invalidateAuth();
        }
        if (resStatus != HttpStatus.SC_OK) {
            throw new NetworkException("Invalid HTTP status " + resStatus + ": " + url + ".");
        }
    } catch (final IOException exception) {
        if (exception.getMessage() != null && exception.getMessage().contains("authentication")) {
            ReaderAccountMgr.getInstance().invalidateAuth();
        }
        throw exception;
    }
    return conn.getInputStream();
}

From source file:com.trk.aboutme.facebook.android.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//  w w w  . j  ava  2  s.c  om
 * @throws MalformedURLException - if the URL format is invalid
 * @throws IOException - if a network problem occurs
 */
@Deprecated
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);
    }
    Utility.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()) {
            Object parameter = params.get(key);
            if (parameter instanceof byte[]) {
                dataparams.putByteArray(key, (byte[]) parameter);
            }
        }

        // 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:de.akquinet.engineering.vaadinator.timesheet.service.AbstractCouchDbService.java

protected JSONObject putCouch(String urlPart, JSONObject content)
        throws IOException, MalformedURLException, JSONException {
    HttpURLConnection couchConn = null;
    BufferedReader couchRead = null;
    OutputStreamWriter couchWrite = null;
    try {/*www  .j ava 2s  .c om*/
        couchConn = (HttpURLConnection) (new URL(couchUrl + (couchUrl.endsWith("/") ? "" : "/") + urlPart))
                .openConnection();
        couchConn.setRequestMethod("PUT");
        couchConn.setDoInput(true);
        couchConn.setDoOutput(true);
        couchWrite = new OutputStreamWriter(couchConn.getOutputStream());
        couchWrite.write(content.toString());
        couchWrite.flush();
        couchRead = new BufferedReader(new InputStreamReader(couchConn.getInputStream()));
        StringBuffer jsonBuf = new StringBuffer();
        String line = couchRead.readLine();
        while (line != null) {
            jsonBuf.append(line);
            line = couchRead.readLine();
        }
        JSONObject couchObj = new JSONObject(jsonBuf.toString());
        return couchObj;
    } finally {
        if (couchRead != null) {
            couchRead.close();
        }
        if (couchWrite != null) {
            couchWrite.close();
        }
        if (couchConn != null) {
            couchConn.disconnect();
        }
    }
}

From source file:eu.codeplumbers.cosi.api.tasks.DeleteDocumentTask.java

@Override
protected String doInBackground(Void... voids) {
    URL urlO = null;//  w  ww .  ja v a2  s .c o m
    try {
        urlO = new URL(url + remoteId + "/");
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoOutput(false);
        conn.setDoInput(true);

        conn.setRequestMethod("DELETE");

        // read the response
        InputStream in = new BufferedInputStream(conn.getInputStream());

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

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

    } catch (MalformedURLException e) {
        result = "error";
        e.printStackTrace();
        errorMessage = e.getLocalizedMessage();
    } catch (ProtocolException e) {
        result = "error";
        errorMessage = e.getLocalizedMessage();
        e.printStackTrace();
    } catch (IOException e) {
        result = "error";
        errorMessage = e.getLocalizedMessage();
        e.printStackTrace();
    }

    return result;
}

From source file:cn.garymb.wechatmoments.common.OkHttpStack.java

private HttpURLConnection openOkHttpURLConnection(OkUrlFactory factory, URL url, Request<?> request)
        throws IOException {
    HttpURLConnection connection = factory.open(url);
    int timeoutMs = request.getTimeoutMs();
    connection.setConnectTimeout(timeoutMs);
    connection.setReadTimeout(timeoutMs);
    connection.setUseCaches(false);/*w w  w . j ava 2 s  .co  m*/
    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.eyekabob.util.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 w  w  . j av  a2s .co m
 * @throws MalformedURLException - if the URL format is invalid
 * @throws IOException - if a network problem occurs
 */
// COFFBR01 MODIFIED
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()) {
            Object value = params.get(key);
            if (value instanceof byte[]) {
                dataparams.putByteArray(key, (byte[]) value);
            }
        }

        // 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;
}