Example usage for java.net HttpURLConnection setDoOutput

List of usage examples for java.net HttpURLConnection setDoOutput

Introduction

In this page you can find the example usage for java.net HttpURLConnection setDoOutput.

Prototype

public void setDoOutput(boolean dooutput) 

Source Link

Document

Sets the value of the doOutput field for this URLConnection to the specified value.

Usage

From source file:com.javielinux.utils.Translate.java

/**
 * Forms an HTTP request and parses the response for a translation.
 *
 * @param text The String to translate./*from  w w w.  j ava2 s.c  om*/
 * @param from The language code to translate from.
 * @param to The language code to translate to.
 * @return The translated String.
 * @throws Exception
 */
private static String retrieveTranslation(String text, String from, String to) throws Exception {
    try {
        StringBuilder url = new StringBuilder();
        url.append(URL_STRING).append(from).append("%7C").append(to);
        url.append(TEXT_VAR).append(URLEncoder.encode(text, ENCODING));

        Log.d(Utils.TAG, "Conectadndo a " + url.toString());
        HttpURLConnection uc = (HttpURLConnection) new URL(url.toString()).openConnection();
        uc.setDoInput(true);
        uc.setDoOutput(true);
        try {
            InputStream is = uc.getInputStream();
            String result = toString(is);

            JSONObject json = new JSONObject(result);
            return ((JSONObject) json.get("responseData")).getString("translatedText");
        } finally { // http://java.sun.com/j2se/1.5.0/docs/guide/net/http-keepalive.html
            uc.getInputStream().close();
            if (uc.getErrorStream() != null)
                uc.getErrorStream().close();
        }
    } catch (Exception ex) {
        throw ex;
    }
}

From source file:com.beust.android.translate.Translate.java

/**
 * Forms an HTTP request and parses the response for a translation.
 *
 * @param text The String to translate./*  w w  w .  ja v a 2s  . c  o m*/
 * @param from The language code to translate from.
 * @param to The language code to translate to.
 * @return The translated String.
 * @throws Exception
 */
private static String retrieveTranslation(String text, String from, String to) throws Exception {
    try {
        StringBuilder url = new StringBuilder();
        url.append(URL_STRING).append(from).append("%7C").append(to);
        url.append(TEXT_VAR).append(URLEncoder.encode(text, ENCODING));

        Log.d(TranslateService.TAG, "Connecting to " + url.toString());
        HttpURLConnection uc = (HttpURLConnection) new URL(url.toString()).openConnection();
        uc.setDoInput(true);
        uc.setDoOutput(true);
        try {
            Log.d(TranslateService.TAG, "getInputStream()");
            InputStream is = uc.getInputStream();
            String result = toString(is);

            JSONObject json = new JSONObject(result);
            return ((JSONObject) json.get("responseData")).getString("translatedText");
        } finally { // http://java.sun.com/j2se/1.5.0/docs/guide/net/http-keepalive.html
            uc.getInputStream().close();
            if (uc.getErrorStream() != null)
                uc.getErrorStream().close();
        }
    } catch (Exception ex) {
        throw ex;
    }
}

From source file:com.itwizard.mezzofanti.Translate.java

/**
 * Forms an HTTP request and parses the response for a translation.
 *
 * @param text The String to translate./*w  w w.j  a  v  a  2  s . com*/
 * @param from The language code to translate from.
 * @param to The language code to translate to.
 * @return The translated String.
 * @throws Exception
 */
private static String retrieveTranslation(String text, String from, String to) throws Exception {
    try {
        StringBuilder url = new StringBuilder();
        url.append(URL_STRING).append(from).append("%7C").append(to);
        url.append(TEXT_VAR).append(URLEncoder.encode(text, ENCODING));

        Log.d("TEST", "Connecting to " + url.toString());
        HttpURLConnection uc = (HttpURLConnection) new URL(url.toString()).openConnection();
        uc.setDoInput(true);
        uc.setDoOutput(true);
        try {
            Log.d("TEST", "getInputStream()");
            InputStream is = uc.getInputStream();
            String result = toString(is);

            JSONObject json = new JSONObject(result);
            return ((JSONObject) json.get("responseData")).getString("translatedText");
        } finally { // http://java.sun.com/j2se/1.5.0/docs/guide/net/http-keepalive.html
            uc.getInputStream().close();
            if (uc.getErrorStream() != null)
                uc.getErrorStream().close();
        }
    } catch (Exception ex) {
        throw ex;
    }
}

From source file:Main.java

/**
 * Issue a POST request to the server.//from w  w  w.  j  ava  2s .co  m
 *
 * @param endpoint
 *            POST address.
 * @param params
 *            request parameters.
 *
 * @throws IOException
 *             propagated from POST.
 */
public static String post_t(String endpoint, Map<String, Object> params, String contentType)
        throws IOException {
    URL url;
    try {
        url = new URL(endpoint);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("invalid url: " + endpoint);
    }
    StringBuilder bodyBuilder = new StringBuilder();
    Iterator<Entry<String, Object>> iterator = params.entrySet().iterator();
    // constructs the POST body using the parameters
    while (iterator.hasNext()) {
        Entry<String, Object> param = iterator.next();
        bodyBuilder.append(param.getKey()).append('=').append(param.getValue());
        if (iterator.hasNext()) {
            bodyBuilder.append('&');
        }
    }
    String body = bodyBuilder.toString();
    byte[] bytes = body.getBytes();
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setFixedLengthStreamingMode(bytes.length);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", contentType);
        // post the request
        OutputStream out = conn.getOutputStream();
        out.write(bytes);
        out.close();
        // handle the response
        int status = conn.getResponseCode();
        if (status != 200) {
            throw new IOException("Post failed with error code " + status);
        }

        // Get Response
        InputStream is = conn.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\n');
        }
        rd.close();
        return response.toString();

    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:com.telefonica.iot.perseo.test.Help.java

public static Res sendMethod(String url, String body, String method) throws Exception {
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod(method);/*from ww w  .java  2  s . c o m*/
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(body);
    wr.flush();
    wr.close();
    int responseCode = con.getResponseCode();
    String responseBody = getBodyResponse(con);
    return new Res(responseCode, responseBody);
}

From source file:com.mboarder.util.Translate.java

/**
 * Forms an HTTP request and parses the response for a translation.
 *
 * @param text The String to translate./*from  w  ww . j a  v  a  2s . c o  m*/
 * @param from The language code to translate from.
 * @param to The language code to translate to.
 * @return The translated String.
 * @throws Exception
 */
private static String retrieveTranslation(String text, String from, String to) throws Exception {
    try {
        StringBuilder url = new StringBuilder();
        url.append(URL_STRING).append(from).append("%7C").append(to);
        url.append(TEXT_VAR).append(URLEncoder.encode(text, ENCODING));

        Log.d(TAG, "Connecting to " + url.toString());
        HttpURLConnection uc = (HttpURLConnection) new URL(url.toString()).openConnection();
        uc.setDoInput(true);
        uc.setDoOutput(true);
        try {
            Log.d(TAG, "getInputStream()");
            InputStream is = uc.getInputStream();
            String result = toString(is);

            JSONObject json = new JSONObject(result);
            return ((JSONObject) json.get("responseData")).getString("translatedText");
        } finally { // http://java.sun.com/j2se/1.5.0/docs/guide/net/http-keepalive.html
            uc.getInputStream().close();
            if (uc.getErrorStream() != null)
                uc.getErrorStream().close();
        }
    } catch (Exception ex) {
        throw ex;
    }
}

From source file:Main.java

public static void DownloadFile(String u) {
    try {/*  w  ww.j a v a2  s .c om*/
        Logd(TAG, "Starting download of: " + u);
        URL url = new URL(u);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(true);
        urlConnection.connect();
        //File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        checkStorageDir();
        File storageDir = new File(
                Environment.getExternalStorageDirectory() + "/Android/data/com.nowsci.odm/.storage");
        File file = new File(storageDir, getFileName(u));
        Logd(TAG, "Storage directory: " + storageDir.toString());
        Logd(TAG, "File name: " + file.toString());
        FileOutputStream fileOutput = new FileOutputStream(file);
        InputStream inputStream = urlConnection.getInputStream();
        byte[] buffer = new byte[1024];
        int bufferLength = 0;
        while ((bufferLength = inputStream.read(buffer)) > 0) {
            fileOutput.write(buffer, 0, bufferLength);
        }
        fileOutput.close();
        Logd(TAG, "File written");
    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.cytoscape.app.internal.net.server.CyHttpdImplTest.java

private static HttpURLConnection connectToURL(String urlString, String method) throws Exception {
    final URL url = new URL(urlString);
    final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(method);
    connection.setDoOutput(true);
    connection.connect();//from   ww  w  . java  2s  . c  o  m
    return connection;
}

From source file:com.github.thorqin.webapi.oauth2.OAuthClient.java

public static AccessToken obtainAccessTokenByCode(String authorityServerUri, String clientId,
        String clientSecret, String code, String redirectUri, boolean useBasicAuthentication)
        throws IOException, OAuthException {
    String rawData = makeObtainAccessTokenByCode(clientId, clientSecret, code, redirectUri,
            useBasicAuthentication);/*from   www .j a v  a2  s .c  o m*/
    String type = "application/x-www-form-urlencoded";
    URL u = new URL(authorityServerUri);
    HttpURLConnection conn = (HttpURLConnection) u.openConnection();
    conn.setDoOutput(true);
    if (useBasicAuthentication) {
        String basicAuthentication = Base64.encodeBase64String((clientId + ":" + clientSecret).getBytes());
        conn.setRequestProperty("Authorization", "Basic " + basicAuthentication);
    }
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", type);
    conn.setRequestProperty("Content-Length", String.valueOf(rawData.length()));
    try (OutputStream os = conn.getOutputStream()) {
        os.write(rawData.getBytes());
    }
    try (InputStream is = conn.getInputStream(); InputStreamReader reader = new InputStreamReader(is)) {
        AccessTokenResponse token = Serializer.fromJson(reader, AccessTokenResponse.class);
        if (token.error != null) {
            throw new OAuthException(token.error, token.errorDescription, token.errorUri);
        }
        return token;
    }
}

From source file:chen.android.toolkit.network.HttpConnection.java

/**
 * </br><b>title : </b>      ????POST??
 * </br><b>description :</b>????POST??
 * </br><b>time :</b>      2012-7-8 ?4:34:08
 * @param method         ??/*from   www .j  a  v  a 2s .  com*/
 * @param url            POSTURL
 * @param datas            ????
 * @return               ???
 * @throws IOException
 */
private static InputStream connect(String method, URL url, byte[]... datas) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestMethod(method);
    conn.setUseCaches(false);
    conn.setInstanceFollowRedirects(true);
    conn.setConnectTimeout(6 * 1000);
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("Charset", "UTF-8");
    OutputStream outputStream = conn.getOutputStream();
    for (byte[] data : datas) {
        outputStream.write(data);
    }
    outputStream.close();
    return conn.getInputStream();
}