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:com.vinexs.tool.NetworkManager.java

public static void haveInternet(Context context, final OnInternetResponseListener listener) {
    if (!haveNetwork(context)) {
        listener.onResponsed(false);//w w w  .j a  v  a2s  . com
        return;
    }
    Log.d("Network", "Check internet is reachable ...");
    new AsyncTask<Void, Integer, Boolean>() {
        @Override
        protected Boolean doInBackground(Void... params) {
            try {
                InetAddress ipAddr = InetAddress.getByName("google.com");
                if (ipAddr.toString().equals("")) {
                    throw new Exception("Cannot resolve host name, no internet behind network.");
                }
                HttpURLConnection conn = (HttpURLConnection) new URL("http://google.com/").openConnection();
                conn.setInstanceFollowRedirects(false);
                conn.setConnectTimeout(3500);
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setRequestMethod("POST");
                DataOutputStream postOutputStream = new DataOutputStream(conn.getOutputStream());
                postOutputStream.write('\n');
                postOutputStream.close();
                conn.disconnect();
                Log.d("Network", "Internet is reachable.");
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
            Log.d("Network", "Internet is unreachable.");
            return false;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            listener.onResponsed(result);
        }
    }.execute();
}

From source file:com.sungtech.goodTeacher.action.TeacherInfoAction.java

public static String httpUrlRequest(String requestURL, String json) {
    URL url;/*www .  j av  a2s .co m*/
    String response = "";
    HttpURLConnection connection = null;
    InputStream is = null;
    try {
        url = new URL(requestURL);

        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.getOutputStream().write(json.getBytes());
        connection.getOutputStream().flush();
        connection.getOutputStream().close();
        int code = connection.getResponseCode();
        System.out.println("code" + code);

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        connection.disconnect();
    }
    return response;
}

From source file:com.github.terma.m.node.Node.java

private static void send(final String serverHost, final int serverPort, final String context,
        final List<Event> events) throws IOException {
    final HttpURLConnection connection = (HttpURLConnection) new URL("http", serverHost, serverPort,
            context + "/node").openConnection();
    connection.setDoOutput(true);/*from  ww w.j  av a  2s .co m*/
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "text/json");
    connection.setRequestProperty("charset", "utf-8");
    connection.setUseCaches(false);
    connection.setInstanceFollowRedirects(false);
    connection.connect();
    OutputStream outputStream = connection.getOutputStream();
    outputStream.write(new Gson().toJson(events).getBytes());
    connection.getInputStream().read();
    outputStream.close();
}

From source file:com.hackerati.android.user_sdk.volley.HHurlStack.java

private static void addBodyIfExists(final HttpURLConnection connection, final Request<?> request)
        throws IOException, AuthFailureError {
    final byte[] body = request.getBody();
    if (body != null) {
        connection.setDoOutput(true);//from  w w w.  ja v  a  2  s.  c  o m
        connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType());
        final DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.write(body);
        out.close();
    }
}

From source file:com.beginner.core.utils.SmsUtil.java

public static String SMS(String postData, String postUrl) {
    try {/*from  w ww.  j a  v  a 2 s.  co  m*/
        //??POST
        URL url = new URL(postUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setUseCaches(false);
        conn.setDoOutput(true);

        conn.setRequestProperty("Content-Length", "" + postData.length());
        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
        out.write(postData);
        out.flush();
        out.close();

        //???
        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            System.out.println("connect failed!");
            return "";
        }
        //??
        String line, result = "";
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
        while ((line = in.readLine()) != null) {
            result += line + "\n";
        }
        in.close();
        return result;
    } catch (IOException e) {
        e.printStackTrace(System.out);
    }
    return "";
}

From source file:net.daporkchop.porkbot.util.HTTPUtils.java

/**
 * Performs a POST request to the specified URL and returns the result.
 * <p/>/*from w w w  .j  a  v a  2 s  .  c  o m*/
 * The POST data will be encoded in UTF-8 as the specified contentType. The response will be parsed as UTF-8.
 * If the server returns an error but still provides a body, the body will be returned as normal.
 * If the server returns an error without any body, a relevant {@link java.io.IOException} will be thrown.
 *
 * @param url         URL to submit the POST request to
 * @param post        POST data in the correct format to be submitted
 * @param contentType Content type of the POST data
 * @return Raw text response from the server
 * @throws IOException The request was not successful
 */
public static String performPostRequestWithAuth(@NonNull URL url, @NonNull String post,
        @NonNull String contentType, @NonNull String auth) throws IOException {
    final HttpURLConnection connection = createUrlConnection(url);
    final byte[] postAsBytes = post.getBytes(Charsets.UTF_8);

    connection.setRequestProperty("Authorization", auth);
    connection.setRequestProperty("Content-Type", contentType + "; charset=utf-8");
    connection.setRequestProperty("Content-Length", "" + postAsBytes.length);
    connection.setDoOutput(true);

    OutputStream outputStream = null;
    try {
        outputStream = connection.getOutputStream();
        IOUtils.write(postAsBytes, outputStream);
    } finally {
        IOUtils.closeQuietly(outputStream);
    }

    return sendRequest(connection);
}

From source file:Main.java

public static String httpPost(String urlStr, List<NameValuePair> params) {

    String paramsEncoded = "";
    if (params != null) {
        paramsEncoded = URLEncodedUtils.format(params, "UTF-8");
    }//  w ww . j a  v a  2 s . com

    String result = null;
    URL url = null;
    HttpURLConnection connection = null;
    InputStreamReader in = null;
    try {
        url = new URL(urlStr);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Charset", "utf-8");
        DataOutputStream dop = new DataOutputStream(connection.getOutputStream());
        dop.writeBytes(paramsEncoded);
        dop.flush();
        dop.close();

        in = new InputStreamReader(connection.getInputStream());
        BufferedReader bufferedReader = new BufferedReader(in);
        StringBuffer strBuffer = new StringBuffer();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            strBuffer.append(line);
        }
        result = strBuffer.toString();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
    return result;
}

From source file:Main.java

/**
 * Issue a POST request to the server.//from www  . j  av a  2  s. co  m
 *
 * @param endpoint POST address.
 * @param params request parameters.
 * @return response
 * @throws IOException propagated from POST.
 */
private static String executePost(String endpoint, Map<String, String> params) throws IOException {
    URL url;
    StringBuffer response = new StringBuffer();
    try {
        url = new URL(endpoint);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("invalid url: " + endpoint);
    }
    StringBuilder bodyBuilder = new StringBuilder();
    Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
    // constructs the POST body using the parameters
    while (iterator.hasNext()) {
        Entry<String, String> param = iterator.next();
        bodyBuilder.append(param.getKey()).append('=').append(param.getValue());
        if (iterator.hasNext()) {
            bodyBuilder.append('&');
        }
    }
    String body = bodyBuilder.toString();
    //Log.v(TAG, "Posting '" + body + "' to " + url);
    byte[] bytes = body.getBytes();
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setFixedLengthStreamingMode(bytes.length);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");

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

        } else {
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
        }
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
    return response.toString();
}

From source file:lu.list.itis.dkd.aig.util.FusekiHttpHelper.java

/**
 * Create a new dataset/*from   w  w  w.jav a2 s  .c om*/
 * 
 * @param dataSetName
 * @throws IOException
 * @throws HttpException
 */
public static void createDataSet(@NonNull String dataSetName) throws IOException, HttpException {
    logger.info("create dataset: " + dataSetName);

    URL url = new URL(HOST + "/$/datasets");
    final HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
    httpConnection.setUseCaches(false);
    httpConnection.setRequestMethod("POST");
    httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    // set content
    httpConnection.setDoOutput(true);
    final OutputStreamWriter out = new OutputStreamWriter(httpConnection.getOutputStream());
    out.write("dbName=" + URLEncoder.encode(dataSetName, "UTF-8") + "&dbType=mem");
    out.close();

    // handle HTTP/HTTPS strange behaviour
    httpConnection.connect();
    httpConnection.disconnect();

    // handle response
    switch (httpConnection.getResponseCode()) {
    case HttpURLConnection.HTTP_OK:
        break;
    default:
        throw new HttpException(
                httpConnection.getResponseCode() + " message: " + httpConnection.getResponseMessage());
    }
}

From source file:com.fluidops.iwb.luxid.LuxidExtractor.java

public static String useLuxidWS(String input, String token, String outputFormat, String annotationPlan)
        throws Exception {
    String s = "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd="
            + "\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"> "
            + "<SOAP-ENV:Body> <ns1:annotateString xmlns:ns1=\"http://luxid.temis.com/ws/types\"> "
            + "<ns1:sessionKey>" + token + "</ns1:sessionKey> <ns1:plan>" + annotationPlan
            + "</ns1:plan> <ns1:data>";

    s += input;// "This is a great providing test";

    s += "</ns1:data> <ns1:consumer>" + outputFormat + "</ns1:consumer> </ns1:annotateString> </SOAP-ENV:Body> "
            + "</SOAP-ENV:Envelope>";

    URL url = new URL("http://193.104.205.28//LuxidWS/services/Annotation");

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);/*from w w w  .j a va  2 s .  c  o m*/

    conn.getOutputStream().write(s.getBytes());

    StringBuilder res = new StringBuilder();

    if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
        InputStream stream = conn.getInputStream();

        InputStreamReader read = new InputStreamReader(stream);
        BufferedReader rd = new BufferedReader(read);

        String line = "";

        StringEscapeUtils.escapeHtml("");
        while ((line = rd.readLine()) != null) {
            res.append(line);
        }
        rd.close();
    }
    //      res = URLDecoder.decode(res, "UTF-8");
    return StringEscapeUtils.unescapeHtml(res.toString().replace("&amp;lt", "<"));
}