Example usage for java.net HttpURLConnection getOutputStream

List of usage examples for java.net HttpURLConnection getOutputStream

Introduction

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

Prototype

public OutputStream getOutputStream() throws IOException 

Source Link

Document

Returns an output stream that writes to this connection.

Usage

From source file:Main.java

public static JSONObject updateRequest(String query) {
    HttpURLConnection connection = null;
    try {//from  w w  w. j  a v a2 s .  co  m
        connection = (HttpURLConnection) new URL(url + query).openConnection();
        connection.setRequestMethod("PUT");
        connection.setRequestProperty("Accept-Charset", charset);

        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
        out.write("Resource content");
        out.close();

        statusCode = connection.getResponseCode();
        if (statusCode != 200) {
            return null;
        }

        InputStream response = connection.getInputStream();
        BufferedReader bR = new BufferedReader(new InputStreamReader(response));
        String line = "";

        StringBuilder responseStrBuilder = new StringBuilder();
        while ((line = bR.readLine()) != null) {
            responseStrBuilder.append(line);
        }
        response.close();
        return new JSONObject(responseStrBuilder.toString());

    } catch (IOException | JSONException e) {
        e.printStackTrace();
    }
    return new JSONObject();
}

From source file:Main.java

public static String post(String url, Map<String, String> params) {
    try {/*from   w  w  w. j a va2s. c om*/
        URL u = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) u.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        PrintWriter pw = new PrintWriter(connection.getOutputStream());
        StringBuilder sbParams = new StringBuilder();
        if (params != null) {
            for (String key : params.keySet()) {
                sbParams.append(key + "=" + params.get(key) + "&");
            }
        }
        if (sbParams.length() > 0) {
            String strParams = sbParams.substring(0, sbParams.length() - 1);
            Log.e("cat", "strParams:" + strParams);
            pw.write(strParams);
            pw.flush();
            pw.close();
        }
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuffer response = new StringBuffer();
        String readLine = "";
        while ((readLine = br.readLine()) != null) {
            response.append(readLine);
        }
        br.close();
        return response.toString();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:ee.ria.xroad.signer.certmanager.OcspClient.java

private static void sendRequest(HttpURLConnection connection, OCSPReq ocspRequest) throws IOException {
    try (DataOutputStream outStream = new DataOutputStream(
            new BufferedOutputStream(connection.getOutputStream()))) {
        outStream.write(ocspRequest.getEncoded());
    }//from  www. j  a v  a  2 s .  co m
}

From source file:Main.java

/**
 * Uses http to post an XML String to a URL.
 *
 * @param url/* w  ww.  j  a v a  2s .c  o m*/
 * @param xmlString
 * @param return
 * @throws IOException
 * @throws UnknownHostException
 */
public static HttpURLConnection post(String url, String xmlString) throws IOException, UnknownHostException {

    // open connection
    URL urlObject = new URL(url);
    HttpURLConnection connection = (HttpURLConnection) urlObject.openConnection();
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "text/xml; charset=\"utf-8\"");
    connection.setDoOutput(true);

    OutputStreamWriter outStream = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
    outStream.write(xmlString);
    outStream.close();

    return connection;
}

From source file:org.elegosproject.romupdater.DownloadManager.java

public static boolean sendAnonymousData() {
    String link = "http://www.elegosproject.org/android/upload.php";
    String data;/* w w  w . j  a v  a2s.c o m*/

    SharedData shared = SharedData.getInstance();
    String romName = shared.getRepositoryROMName();
    String romVersion = shared.getDownloadVersion();
    String romPhone = shared.getRepositoryModel();
    String romRepository = shared.getRepositoryUrl();

    if (romName.equals("") || romVersion.equals("") || romPhone.equals("") || romRepository.equals("")) {
        Log.e(TAG, "Internal error - missing system variables.");
        return false;
    }

    if (!checkHttpFile(link))
        return false;
    try {
        data = URLEncoder.encode("phone", "UTF-8") + "=" + URLEncoder.encode(romPhone, "UTF-8");
        data += "&" + URLEncoder.encode("rom_name", "UTF-8") + "=" + URLEncoder.encode(romName, "UTF-8");
        data += "&" + URLEncoder.encode("rom_version", "UTF-8") + "=" + URLEncoder.encode(romVersion, "UTF-8");
        data += "&" + URLEncoder.encode("rom_repository", "UTF-8") + "="
                + URLEncoder.encode(romRepository, "UTF-8");

        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 3000);

        URL url = new URL(link);
        url.openConnection();
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("User-Agent", "ROMUpdater");
        conn.setDoOutput(true);
        PrintWriter out = new PrintWriter(conn.getOutputStream());
        out.println(data);
        out.close();

        int status = Integer.parseInt(conn.getHeaderField("ROMUpdater-status"));
        if (status == 1)
            return true;

        Log.e(TAG, "It was impossible to send data to the stastistics server ("
                + conn.getHeaderField("ROMUpdater-error") + ").");
        return false;

    } catch (Exception e) {
        Log.e(TAG, "It was impossible to send data to the stastistics server.");
        Log.e(TAG, "Error: " + e.toString());
        return false;
    }
}

From source file:Main.java

public static String stringFromHttpPost(String urlStr, String body) {
    HttpURLConnection conn;
    try {/*from w w w.  java 2  s  . c  o  m*/
        URL e = new URL(urlStr);
        conn = (HttpURLConnection) e.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setInstanceFollowRedirects(true);
        conn.setRequestMethod("POST");
        OutputStream os1 = conn.getOutputStream();
        DataOutputStream out1 = new DataOutputStream(os1);
        out1.write(body.getBytes("UTF-8"));
        out1.flush();
        conn.connect();
        String line;
        BufferedReader reader;
        StringBuffer sb = new StringBuffer();
        if ("gzip".equals(conn.getHeaderField("Content-Encoding"))) {
            reader = new BufferedReader(
                    new InputStreamReader(new GZIPInputStream(conn.getInputStream()), "UTF-8"));
        } else {
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        }
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        return sb.toString();
    } catch (Exception e) {
        e.printStackTrace();
        logError(e.getMessage());
    }
    return null;
}

From source file:com.google.api.GoogleAPI.java

/**
 * Forms an HTTP request, sends it using POST method and returns the result of the request as a JSONObject.
 * /*w  w w  .j  a v  a2s  . c  o m*/
 * @param url The URL to query for a JSONObject.
 * @param parameters Additional POST parameters
 * @return The translated String.
 * @throws Exception on error.
 */
protected static JSONObject retrieveJSON(final URL url, final String parameters) throws Exception {
    try {
        final HttpURLConnection uc = (HttpURLConnection) url.openConnection();
        uc.setRequestProperty("referer", referrer);
        uc.setRequestMethod("POST");
        uc.setDoOutput(true);

        final PrintWriter pw = new PrintWriter(uc.getOutputStream());
        pw.write(parameters);
        pw.flush();

        try {
            final String result = inputStreamToString(uc.getInputStream());

            return new JSONObject(result);
        } 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();
            }
            pw.close();
        }
    } catch (Exception ex) {
        throw new Exception("[google-api-translate-java] Error retrieving translation.", ex);
    }
}

From source file:com.company.project.core.connector.HttpClientHelper.java

public static String getResponseStringFromConn(HttpURLConnection conn, String payLoad) throws IOException {

    // Send the http message payload to the server.
    if (payLoad != null) {
        conn.setDoOutput(true);//from   w w  w.j ava2 s. c om
        OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream());
        osw.write(payLoad);
        osw.flush();
        osw.close();
    }

    // Get the message response from the server.
    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line = "";
    StringBuffer stringBuffer = new StringBuffer();
    while ((line = br.readLine()) != null) {
        stringBuffer.append(line);
    }

    br.close();

    return stringBuffer.toString();
}

From source file:Main.java

private static HttpURLConnection defineHttpsURLConnection(HttpURLConnection connection, JSONObject jsonObject) {
    try {/*from w  w  w .j a v  a  2s.  co m*/
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        /* Add headers to the request */
        connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");

        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.write(jsonObject.toString().getBytes(Charset.forName("UTF-8")));
        wr.flush();
        wr.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return connection;
}

From source file:Authentication.DinserverAuth.java

public static boolean Login(String nick, String pass, Socket socket) throws IOException {
    boolean logged = false;

    JSONObject authRequest = new JSONObject();
    authRequest.put("username", nick);
    authRequest.put("auth_id", pass);

    String query = "http://127.0.0.1:5000/token";

    URL url = new URL(query);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setConnectTimeout(5000);// w ww.j av a2 s . c  o m
    conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestMethod("POST");

    OutputStream os = conn.getOutputStream();
    os.write(authRequest.toString().getBytes(Charset.forName("UTF-8")));
    os.close();
    String output = new String();
    StringBuilder sb = new StringBuilder();
    int HttpResult = conn.getResponseCode();
    if (HttpResult == HttpURLConnection.HTTP_OK) {
        output = IOUtils.toString(new InputStreamReader(conn.getInputStream(), Charset.forName("UTF-8")));
    } else {
        System.out.println(conn.getResponseMessage());
    }

    JSONObject jsonObject = new JSONObject(output);
    logged = jsonObject.getBoolean("ok");

    conn.disconnect();

    if (logged) {
        if (DinserverMaster.addUser(nick, socket)) {
            System.out.println("User " + nick + " logged in");
        } else {
            logged = false;
        }
    }
    return logged;
}