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.comcast.cmb.test.tools.CNSTestingUtils.java

public static String sendHttpMessage(String endpoint, String message) throws Exception {

    if ((message == null) || (endpoint == null)) {
        throw new Exception("Message and Endpoint must both be set");
    }// w  ww.j  av  a  2s  . c  om

    String newPostBody = message;
    byte newPostBodyBytes[] = newPostBody.getBytes();

    URL url = new URL(endpoint);

    logger.info(">> " + url.toString());

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

    con.setRequestMethod("GET"); // POST no matter what
    con.setDoOutput(true);
    con.setDoInput(true);
    con.setFollowRedirects(false);
    con.setUseCaches(true);

    logger.info(">> " + "GET");

    //con.setRequestProperty("content-length", newPostBody.length() + "");
    con.setRequestProperty("host", url.getHost());

    con.connect();

    logger.info(">> " + newPostBody);

    int statusCode = con.getResponseCode();

    BufferedInputStream responseStream;

    logger.info("StatusCode:" + statusCode);

    if (statusCode != 200 && statusCode != 201) {

        responseStream = new BufferedInputStream(con.getErrorStream());
    } else {
        responseStream = new BufferedInputStream(con.getInputStream());
    }

    int b;
    String response = "";

    while ((b = responseStream.read()) != -1) {
        response += (char) b;
    }

    logger.info("response:" + response);
    return response;
}

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

@SuppressWarnings("deprecation")
/* package */static void setConnectionParametersForRequest(final HttpURLConnection connection,
        final Request<?> request) throws IOException, AuthFailureError {
    switch (request.getMethod()) {
    case Method.DEPRECATED_GET_OR_POST:
        // This is the deprecated way that needs to be handled for backwards
        // compatibility.
        // If the request's post body is null, then the assumption is that
        // the request is
        // GET. Otherwise, it is assumed that the request is a POST.
        final byte[] postBody = request.getPostBody();
        if (postBody != null) {
            // Prepare output. There is no need to set Content-Length
            // explicitly,
            // since this is handled by HttpURLConnection using the size of
            // the prepared
            // output stream.
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
            final DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.write(postBody);/*  ww w .j  a v a  2  s  .  c  om*/
            out.close();
        }
        break;
    case Method.GET:
        // Not necessary to set the request method because connection
        // defaults to GET but
        // being explicit here.
        connection.setRequestMethod("GET");
        break;
    case Method.DELETE:
        connection.setRequestMethod("DELETE");
        break;
    case Method.POST:
        connection.setRequestMethod("POST");
        addBodyIfExists(connection, request);
        break;
    case Method.PUT:
        connection.setRequestMethod("PUT");
        addBodyIfExists(connection, request);
        break;
    case Method.HEAD:
        connection.setRequestMethod("HEAD");
        break;
    case Method.OPTIONS:
        connection.setRequestMethod("OPTIONS");
        break;
    case Method.TRACE:
        connection.setRequestMethod("TRACE");
        break;
    case Method.PATCH:
        addBodyIfExists(connection, request);
        connection.setRequestMethod("PATCH");
        break;
    default:
        throw new IllegalStateException("Unknown method type.");
    }
}

From source file:com.yaozu.object.volley.toolbox.HurlStack.java

@SuppressWarnings("deprecation")
/* package */static void setConnectionParametersForRequest(HttpURLConnection connection, Request<?> request)
        throws IOException, AuthFailureError {
    switch (request.getMethod()) {
    case Request.Method.DEPRECATED_GET_OR_POST:
        // This is the deprecated way that needs to be handled for backwards
        // compatibility.
        // If the request's post body is null, then the assumption is that
        // the request is
        // GET. Otherwise, it is assumed that the request is a POST.
        byte[] postBody = request.getPostBody();
        if (postBody != null) {
            // Prepare output. There is no need to set Content-Length
            // explicitly,
            // since this is handled by HttpURLConnection using the size of
            // the prepared
            // output stream.
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.write(postBody);//from w w w  .j  av a 2s  .c  o m
            out.close();
        }
        break;
    case Request.Method.GET:
        // Not necessary to set the request method because connection
        // defaults to GET but
        // being explicit here.
        connection.setRequestMethod("GET");
        break;
    case Request.Method.DELETE:
        connection.setRequestMethod("DELETE");
        break;
    case Request.Method.POST:
        connection.setRequestMethod("POST");
        addBodyIfExists(connection, request);
        break;
    case Request.Method.PUT:
        connection.setRequestMethod("PUT");
        addBodyIfExists(connection, request);
        break;
    case Request.Method.HEAD:
        connection.setRequestMethod("HEAD");
        break;
    case Request.Method.OPTIONS:
        connection.setRequestMethod("OPTIONS");
        break;
    case Request.Method.TRACE:
        connection.setRequestMethod("TRACE");
        break;
    case Request.Method.PATCH:
        connection.setRequestMethod("PATCH");
        addBodyIfExists(connection, request);
        break;
    default:
        throw new IllegalStateException("Unknown method type.");
    }
}

From source file:org.csware.ee.utils.Tools.java

public static String reqByPostSI(String path, String cookie, String params) {
    String info = "";
    String sessionId = "";
    try {/*  www .  j  a  v a2 s .  c  om*/
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(20000);
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        // conn.setDoInput(true);

        //            conn.setInstanceFollowRedirects(isJump);

        conn.setRequestProperty("Cookie", cookie);
        conn.setRequestProperty("Connection", "keep-alive");
        conn.setRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
        conn.setRequestProperty("Cache-Control", "max-age=0");
        conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
        conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8");
        conn.setRequestProperty("Accept",
                "application/json,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        //            conn.setRequestProperty("Host", "creditcardapp.bankcomm.com");
        //            conn.setRequestProperty("Origin", "https://creditcardapp.bankcomm.com");
        //            conn.setRequestProperty("Referer", "https://creditcardapp.bankcomm.com/member/home/index.html");
        conn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36");

        //
        byte[] bypes = params.getBytes();
        OutputStream os = conn.getOutputStream();
        os.write(bypes);// ?
        os.flush();
        os.close();

        InputStream in = conn.getInputStream();
        //            System.out.println(conn.getHeaderField("Set-Cookie"));

        try {

            byte[] buffer = new byte[65536];
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int readLength = in.read(buffer);
            long totalLength = 0;
            while (readLength >= 0) {
                bos.write(buffer, 0, readLength);
                totalLength = totalLength + readLength;
                readLength = in.read(buffer);

            }
            info = bos.toString("UTF-8");
        } finally {
            if (in != null)
                try {
                    in.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
        }
        // 
        //conn.setConnectTimeout(5 * 1000);
        // 
        // conn.connect();
    } catch (Exception ex) {
        ex.printStackTrace();

        return "";
    }
    return info;

}

From source file:com.flozano.socialauth.util.HttpUtil.java

/**
 *
 * @param urlStr/*from   w ww. j a v  a  2s .c o m*/
 *            the URL String
 * @param requestMethod
 *            Method type
 * @param params
 *            Parameters to pass in request
 * @param header
 *            Header parameters
 * @param inputStream
 *            Input stream of image
 * @param fileName
 *            Image file name
 * @param fileParamName
 *            Image Filename parameter. It requires in some provider.
 * @return Response object
 * @throws SocialAuthException
 */
public static Response doHttpRequest(final String urlStr, final String requestMethod,
        final Map<String, String> params, final Map<String, String> header, final InputStream inputStream,
        final String fileName, final String fileParamName, Optional<ConnectionSettings> connectionSettings)
        throws SocialAuthException {
    HttpURLConnection conn;
    try {

        URL url = new URL(urlStr);
        if (proxyObj != null) {
            conn = (HttpURLConnection) url.openConnection(proxyObj);
        } else {
            conn = (HttpURLConnection) url.openConnection();
        }

        connectionSettings.ifPresent(settings -> settings.apply(conn));

        if (requestMethod.equalsIgnoreCase(MethodType.POST.toString())
                || requestMethod.equalsIgnoreCase(MethodType.PUT.toString())) {
            conn.setDoOutput(true);
        }

        conn.setDoInput(true);

        conn.setInstanceFollowRedirects(true);
        if (timeoutValue > 0) {
            LOG.debug("Setting connection timeout : " + timeoutValue);
            conn.setConnectTimeout(timeoutValue);
        }
        if (requestMethod != null) {
            conn.setRequestMethod(requestMethod);
        }
        if (header != null) {
            for (String key : header.keySet()) {
                conn.setRequestProperty(key, header.get(key));
            }
        }

        // If use POST or PUT must use this
        OutputStream os = null;
        if (inputStream != null) {
            if (requestMethod != null && !MethodType.GET.toString().equals(requestMethod)
                    && !MethodType.DELETE.toString().equals(requestMethod)) {
                LOG.debug(requestMethod + " request");
                String boundary = "----Socialauth-posting" + System.currentTimeMillis();
                conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
                boundary = "--" + boundary;

                os = conn.getOutputStream();
                DataOutputStream out = new DataOutputStream(os);
                write(out, boundary + "\r\n");

                if (fileParamName != null) {
                    write(out, "Content-Disposition: form-data; name=\"" + fileParamName + "\"; filename=\""
                            + fileName + "\"\r\n");
                } else {
                    write(out, "Content-Disposition: form-data;  filename=\"" + fileName + "\"\r\n");
                }
                write(out, "Content-Type: " + "multipart/form-data" + "\r\n\r\n");
                int b;
                while ((b = inputStream.read()) != -1) {
                    out.write(b);
                }
                // out.write(imageFile);
                write(out, "\r\n");

                Iterator<Map.Entry<String, String>> entries = params.entrySet().iterator();
                while (entries.hasNext()) {
                    Map.Entry<String, String> entry = entries.next();
                    write(out, boundary + "\r\n");
                    write(out, "Content-Disposition: form-data; name=\"" + entry.getKey() + "\"\r\n\r\n");
                    // write(out,
                    // "Content-Type: text/plain;charset=UTF-8 \r\n\r\n");
                    LOG.debug(entry.getValue());
                    out.write(entry.getValue().getBytes("UTF-8"));
                    write(out, "\r\n");
                }

                write(out, boundary + "--\r\n");
                write(out, "\r\n");
            }
        }
        conn.connect();
    } catch (Exception e) {
        throw new SocialAuthException(e);
    }
    return new Response(conn);

}

From source file:gov.nasa.arc.geocam.geocam.HttpPost.java

public static HttpURLConnection createConnection(String url, String username, String password)
        throws IOException {
    boolean useAuth = !password.equals("");
    // force SSL if useAuth=true (would send password unencrypted otherwise)
    boolean useSSL = useAuth || url.startsWith("https");

    Log.d("HttpPost", "password: " + password);
    Log.d("HttpPost", "useSSL: " + useSSL);

    if (useSSL) {
        if (!url.startsWith("https")) {
            // replace http: with https: -- this will obviously screw
            // up if input is something other than http so don't do that :)
            url = "https:" + url.substring(5);
        }/*from w ww. j  a  va2  s  .c om*/

        // would rather not do this, need to check if there's still a problem
        // with our ssl certificates on NASA servers.
        try {
            DisableSSLCertificateCheckUtil.disableChecks();
        } catch (GeneralSecurityException e) {
            throw new IOException("HttpPost - disable ssl: " + e);
        }
    }

    HttpURLConnection conn;
    try {
        if (useSSL) {
            conn = (HttpsURLConnection) (new URL(url)).openConnection();
        } else {
            conn = (HttpURLConnection) (new URL(url)).openConnection();
        }
    } catch (IOException e) {
        throw new IOException("HttpPost - IOException: " + e);
    }

    if (useAuth) {
        // add pre-emptive http basic authentication.  using
        // homebrew version -- early versions of android
        // authenticator have problems and this is easy.
        String userpassword = username + ":" + password;
        String encodedAuthorization = Base64.encode(userpassword.getBytes());
        conn.setRequestProperty("Authorization", "Basic " + encodedAuthorization);
    }

    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setAllowUserInteraction(true);

    return conn;
}

From source file:com.example.appengine.appidentity.UrlShortener.java

/**
 * Returns a shortened URL by calling the Google URL Shortener API.
 *
 * <p>Note: Error handling elided for simplicity.
 *///  ww  w  .  ja  va 2s. c  om
public String createShortUrl(String longUrl) throws Exception {
    ArrayList<String> scopes = new ArrayList<String>();
    scopes.add("https://www.googleapis.com/auth/urlshortener");
    final AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService();
    final AppIdentityService.GetAccessTokenResult accessToken = appIdentity.getAccessToken(scopes);
    // The token asserts the identity reported by appIdentity.getServiceAccountName()
    JSONObject request = new JSONObject();
    request.put("longUrl", longUrl);

    URL url = new URL("https://www.googleapis.com/urlshortener/v1/url?pp=1");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.addRequestProperty("Content-Type", "application/json");
    connection.addRequestProperty("Authorization", "Bearer " + accessToken.getAccessToken());

    OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
    request.write(writer);
    writer.close();

    if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
        // Note: Should check the content-encoding.
        //       Any JSON parser can be used; this one is used for illustrative purposes.
        JSONTokener responseTokens = new JSONTokener(connection.getInputStream());
        JSONObject response = new JSONObject(responseTokens);
        return (String) response.get("id");
    } else {
        try (InputStream s = connection.getErrorStream();
                InputStreamReader r = new InputStreamReader(s, StandardCharsets.UTF_8)) {
            throw new RuntimeException(String.format("got error (%d) response %s from %s",
                    connection.getResponseCode(), CharStreams.toString(r), connection.toString()));
        }
    }
}

From source file:ai.eve.volley.request.JsonRequest.java

@Override
public void getBody(HttpURLConnection connection) {
    try {// www . ja v  a  2 s .  c  om
        if (mRequestBody != null) {
            connection.setDoOutput(true);
            connection.addRequestProperty(HTTP.CONTENT_TYPE, getBodyContentType());
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.write(mRequestBody.getBytes(PROTOCOL_CHARSET));
            out.close();
        }
    } catch (UnsupportedEncodingException uee) {
        NetroidLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody,
                PROTOCOL_CHARSET);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.writewreckedsoftware.ullr.networking.UpdateMarker.java

@Override
protected String doInBackground(String... arg0) {
    String json = arg0[0];//from w  ww  . j a v a2s  . c o  m
    JSONObject obj = null;
    String id = "";
    try {
        obj = new JSONObject(json);
        id = obj.getString("_id");
    } catch (JSONException e) {
        e.printStackTrace();
    }

    URL url = null;
    String resultText = "";
    try {
        url = new URL("http://ullr.herokuapp.com/markers/" + id);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("PUT");
        connection.setRequestProperty("Content-Type", "application/json");
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
        out.write(json);
        out.close();
        InputStream response = connection.getInputStream();
        resultText = NetworkHelpers.getInstance(null).convertStreamToString(response);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    JSONObject result = null;
    try {
        result = new JSONObject(resultText);
        result.put("_id", id);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return result.toString();
}

From source file:com.ibuildapp.romanblack.CataloguePlugin.utils.Utils.java

/**
 * Likes video with given position./*from www.j ava 2 s.c om*/
 */
public static boolean like(final String innerurl) {
    try {
        String url = "https://graph.facebook.com/me/og.likes";

        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestProperty("Accept-Encoding", "identity");
        conn.setRequestProperty("charset", "utf-8");
        conn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (iPhone; U; " + "CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 "
                        + "(KHTML, like Gecko) Version/4.0.5 Mobile/8A293 " + "Safari/6531.22.7");

        conn.setRequestMethod("POST");
        conn.setDoOutput(true);

        StringBuilder sb = new StringBuilder();
        sb.append("method=");
        sb.append("POST");
        sb.append("&");
        sb.append("access_token=");
        sb.append(Authorization.getAuthorizedUser(Authorization.AUTHORIZATION_TYPE_FACEBOOK).getAccessToken());
        sb.append("&");
        sb.append("object=");
        sb.append(URLEncoder.encode(innerurl));

        String params = sb.toString();

        conn.getOutputStream().write(params.getBytes("UTF-8"));

        String response = "";
        try {
            InputStream in = conn.getInputStream();

            StringBuilder sbr = new StringBuilder();
            BufferedReader r = new BufferedReader(new InputStreamReader(in), 1000);
            for (String line = r.readLine(); line != null; line = r.readLine()) {
                sbr.append(line);
            }
            in.close();

            response = sbr.toString();
        } catch (FileNotFoundException e) {
            InputStream in = conn.getErrorStream();

            StringBuilder sbr = new StringBuilder();
            BufferedReader r = new BufferedReader(new InputStreamReader(in), 1000);
            for (String line = r.readLine(); line != null; line = r.readLine()) {
                sbr.append(line);
            }
            in.close();

            response = sbr.toString();
            Log.e(TAG, "response = " + response);
        }

        try {
            JSONObject obj = new JSONObject(response);
            obj.getString("id");
            return true;

        } catch (JSONException jSONEx) {
            //    fb       
            //                      // ?   ?  ?  ?   ?
            conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setRequestProperty("Accept-Encoding", "identity");
            conn.setRequestProperty("charset", "utf-8");
            conn.setRequestProperty("User-Agent",
                    "Mozilla/5.0 (iPhone; U; " + "CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 "
                            + "(KHTML, like Gecko) Version/4.0.5 Mobile/8A293 " + "Safari/6531.22.7");

            conn.setRequestMethod("POST");
            conn.setDoOutput(true);

            sb = new StringBuilder();
            sb.append("method=");
            sb.append("POST");
            sb.append("&");
            sb.append("access_token=");
            sb.append(Authorization.getAuthorizedUser(Authorization.AUTHORIZATION_TYPE_FACEBOOK)
                    .getAccessToken());
            sb.append("&");
            sb.append("object=");
            sb.append(URLEncoder.encode(innerurl));

            params = sb.toString();

            conn.getOutputStream().write(params.getBytes("UTF-8"));

            try {
                InputStream in = conn.getInputStream();

                StringBuilder sbr = new StringBuilder();
                BufferedReader r = new BufferedReader(new InputStreamReader(in), 1000);
                for (String line = r.readLine(); line != null; line = r.readLine()) {
                    sbr.append(line);
                }
                in.close();

                response = sbr.toString();
                Log.e(TAG, "response2 = " + response);

                try {
                    JSONObject obj = new JSONObject(response);
                    obj.getString("id");
                    return true;
                } catch (JSONException e) {
                    return false;
                }
            } catch (FileNotFoundException e) {
                return false;
            }
        }
    } catch (MalformedURLException mURLEx) {
        Log.d("", "");
        return false;
    } catch (IOException iOEx) {
        Log.d("", "");
        return false;
    } catch (Exception ex) {
        Log.d("", "");
        return false;
    }
}