Example usage for java.net HttpURLConnection setRequestProperty

List of usage examples for java.net HttpURLConnection setRequestProperty

Introduction

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

Prototype

public void setRequestProperty(String key, String value) 

Source Link

Document

Sets the general request property.

Usage

From source file:com.intellij.lang.jsgraphql.languageservice.JSGraphQLNodeLanguageServiceClient.java

private static <R> R executeRequest(Request request, Class<R> responseClass, @NotNull Project project,
        boolean setProjectDir) {

    URL url = getJSGraphQLNodeLanguageServiceInstance(project, setProjectDir);
    if (url == null) {
        return null;
    }//  ww w .j a  va  2 s . com
    HttpURLConnection httpConnection = null;
    try {
        httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.setConnectTimeout(50);
        httpConnection.setReadTimeout(1000);
        httpConnection.setRequestMethod("POST");
        httpConnection.setDoOutput(true);
        httpConnection.setRequestProperty("Content-Type", "application/json");
        httpConnection.connect();
        try (OutputStreamWriter writer = new OutputStreamWriter(httpConnection.getOutputStream())) {
            final String jsonRequest = new Gson().toJson(request);
            writer.write(jsonRequest);
            writer.flush();
            writer.close();
        }
        if (httpConnection.getResponseCode() == 200) {
            if (responseClass == null) {
                return null;
            }
            try (InputStream inputStream = httpConnection.getInputStream()) {
                String jsonResponse = IOUtils.toString(inputStream, "UTF-8");
                R response = new Gson().fromJson(jsonResponse, responseClass);
                return response;
            }
        } else {
            log.warn("Got error from JS GraphQL Language Service: HTTP " + httpConnection.getResponseCode()
                    + ": " + httpConnection.getResponseMessage());
        }
    } catch (IOException e) {
        log.warn("Unable to connect to dev server", e);
    } finally {
        if (httpConnection != null) {
            httpConnection.disconnect();
        }
    }
    return null;
}

From source file:com.openforevent.main.UserPosition.java

public static Map<String, Object> userPositionByIP(DispatchContext ctx, Map<String, ? extends Object> context)
        throws IOException {
    URL url = new URL("http://api.ipinfodb.com/v3/ip-city/?" + "key=" + ipinfodb_key + "&" + "&ip=" + default_ip
            + "&format=xml");
    //URL url = new URL("http://ipinfodb.com/ip_query.php");
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

    // Set properties of the connection
    urlConnection.setRequestMethod("GET");
    urlConnection.setDoInput(true);//from  w  w  w  .  j  a va2 s .  com
    urlConnection.setDoOutput(true);
    urlConnection.setUseCaches(false);
    urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    // Retrieve the output
    int responseCode = urlConnection.getResponseCode();
    InputStream inputStream;
    if (responseCode == HttpURLConnection.HTTP_OK) {
        inputStream = urlConnection.getInputStream();
    } else {
        inputStream = urlConnection.getErrorStream();
    }

    StringWriter writer = new StringWriter();
    IOUtils.copy(inputStream, writer, "UTF-8");
    String theString = writer.toString();

    Debug.logInfo("Get user position by IP stream is = ", theString);

    Map<String, Object> paramOut = FastMap.newInstance();
    paramOut.put("stream", theString);
    return paramOut;
}

From source file:com.google.api.ads.adwords.awreporting.server.appengine.exporter.ReportExporterAppEngine.java

public static void html2PdfOverNet(InputStream htmlSource, ReportWriter reportWriter) {
    try {/*w w w.j a  v a2  s . co m*/
        URL url = new URL(HTML_2_PDF_SERVER_URL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "text/html");
        connection.setRequestProperty("charset", "utf-8");
        connection.setUseCaches(false);

        DataOutputStream send = new DataOutputStream(connection.getOutputStream());
        send.write(IOUtils.toByteArray(htmlSource));
        send.flush();

        // Read from connection
        reportWriter.write(connection.getInputStream());

        send.close();

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

From source file:com.gallatinsystems.common.util.S3Util.java

public static boolean putObjectAcl(String bucketName, String objectKey, ACL acl, String awsAccessId,
        String awsSecretKey) throws IOException {

    final String date = getDate();
    final URL url = new URL(String.format(S3_URL, bucketName, objectKey) + "?acl");
    final String payload = String.format(PUT_PAYLOAD_ACL, date, acl.toString(), bucketName, objectKey);
    final String signature = MD5Util.generateHMAC(payload, awsSecretKey);
    HttpURLConnection conn = null;
    try {/*from w w w. ja va 2 s .c  o  m*/

        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("PUT");
        conn.setRequestProperty("Date", date);
        conn.setRequestProperty("x-amz-acl", acl.toString());
        conn.setRequestProperty("Authorization", "AWS " + awsAccessId + ":" + signature);

        int status = conn.getResponseCode();

        if (status != 200 && status != 201) {
            log.severe("Error setting ACL for: " + url.toString());
            log.severe(IOUtils.toString(conn.getInputStream()));
            return false;
        }
        return true;
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:com.nit.vicky.web.HttpFetcher.java

public static String downloadFileToSdCardMethod(String UrlToFile, Context context, String prefix, String method,
        Boolean isMP3) {//from w w  w .j ava  2  s. c o m
    try {
        URL url = new URL(UrlToFile);

        String extension = ".mp3";

        if (!isMP3)
            extension = UrlToFile.substring(UrlToFile.lastIndexOf("."));

        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setConnectTimeout(10 * 1000);
        urlConnection.setReadTimeout(10 * 1000);
        urlConnection.setRequestMethod(method);
        //urlConnection.setRequestProperty("Referer", "http://mm.taobao.com/");
        urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) ");
        urlConnection.setRequestProperty("Accept", "*/*");
        urlConnection.connect();

        File file = File.createTempFile(prefix, extension, DiskUtil.getStoringDirectory());

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

        return file.getAbsolutePath();

    } catch (Exception e) {
        return "FAILED " + e.getMessage();
    }
}

From source file:bluevia.SendSMS.java

public static void setFacebookWallPost(String userEmail, String post) {
    try {/*from w w w .  j  a  va 2 s .c o m*/

        Properties facebookAccount = Util.getNetworkAccount(userEmail, Util.FaceBookOAuth.networkID);

        if (facebookAccount != null) {
            String access_key = facebookAccount.getProperty(Util.FaceBookOAuth.networkID + ".access_key");

            com.google.appengine.api.urlfetch.FetchOptions.Builder.doNotValidateCertificate();

            Entity blueviaUser = Util.getUser(userEmail);

            //FIXME
            URL fbAPI = new URL(
                    "https://graph.facebook.com/" + (String) blueviaUser.getProperty("alias") + "/feed");
            HttpURLConnection request = (HttpURLConnection) fbAPI.openConnection();

            String content = String.format("access_token=%s&message=%s", access_key,
                    URLEncoder.encode(post, "UTF-8"));

            request.setRequestMethod("POST");
            request.setRequestProperty("Content-Type", "javascript/text");
            request.setRequestProperty("Content-Length", "" + Integer.toString(content.getBytes().length));
            request.setDoOutput(true);
            request.setDoInput(true);

            OutputStream os = request.getOutputStream();
            os.write(content.getBytes());
            os.flush();
            os.close();

            BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
            int rc = request.getResponseCode();
            if (rc == HttpURLConnection.HTTP_OK) {
                StringBuffer body = new StringBuffer();
                String line;

                do {
                    line = br.readLine();
                    if (line != null)
                        body.append(line);
                } while (line != null);

                JSONObject id = new JSONObject(body.toString());
            } else
                log.severe(
                        String.format("Error %d posting FaceBook wall:%s\n", rc, request.getResponseMessage()));
        }
    } catch (Exception e) {
        log.severe(String.format("Exception posting FaceBook wall: %s", e.getMessage()));
    }
}

From source file:Main.java

public static byte[] executePost(String url, byte[] data, Map<String, String> requestProperties)
        throws IOException {
    HttpURLConnection urlConnection = null;
    try {/*from w w w.ja v a  2 s.  c  o  m*/
        urlConnection = (HttpURLConnection) new URL(url).openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoOutput(data != null);
        urlConnection.setDoInput(true);
        if (requestProperties != null) {
            for (Map.Entry<String, String> requestProperty : requestProperties.entrySet()) {
                urlConnection.setRequestProperty(requestProperty.getKey(), requestProperty.getValue());
            }
        }
        if (data != null) {
            OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
            out.write(data);
            out.close();
        }
        InputStream in = new BufferedInputStream(urlConnection.getInputStream());
        return convertInputStreamToByteArray(in);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}

From source file:com.gmt2001.HttpRequest.java

public static HttpResponse getData(RequestType type, String url, String post, HashMap<String, String> headers) {
    Thread.setDefaultUncaughtExceptionHandler(com.gmt2001.UncaughtExceptionHandler.instance());

    HttpResponse r = new HttpResponse();

    r.type = type;//  ww  w  .  j  a v a 2 s .c o m
    r.url = url;
    r.post = post;
    r.headers = headers;

    try {
        URL u = new URL(url);

        HttpURLConnection h = (HttpURLConnection) u.openConnection();

        for (Entry<String, String> e : headers.entrySet()) {
            h.addRequestProperty(e.getKey(), e.getValue());
        }

        h.setRequestMethod(type.name());
        h.setUseCaches(false);
        h.setDefaultUseCaches(false);
        h.setConnectTimeout(timeout);
        h.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 PhantomBotJ/2015");
        if (!post.isEmpty()) {
            h.setDoOutput(true);
        }

        h.connect();

        if (!post.isEmpty()) {
            BufferedOutputStream stream = new BufferedOutputStream(h.getOutputStream());
            stream.write(post.getBytes());
            stream.flush();
            stream.close();
        }

        if (h.getResponseCode() < 400) {
            r.content = IOUtils.toString(new BufferedInputStream(h.getInputStream()), h.getContentEncoding());
            r.httpCode = h.getResponseCode();
            r.success = true;
        } else {
            r.content = IOUtils.toString(new BufferedInputStream(h.getErrorStream()), h.getContentEncoding());
            r.httpCode = h.getResponseCode();
            r.success = false;
        }
    } catch (IOException ex) {
        r.success = false;
        r.httpCode = 0;
        r.exception = ex.getMessage();

        com.gmt2001.Console.err.printStackTrace(ex);
    }

    return r;
}

From source file:com.qpark.eip.core.spring.security.https.HttpsRequester.java

private static String read(final URL url, final String httpAuthBase64, final HostnameVerifier hostnameVerifier)
        throws IOException {
    StringBuffer sb = new StringBuffer(1024);
    HttpURLConnection connection = null;
    connection = (HttpURLConnection) url.openConnection();
    if (url.getProtocol().equalsIgnoreCase("https")) {
        connection = (HttpsURLConnection) url.openConnection();
        ((HttpsURLConnection) connection).setHostnameVerifier(hostnameVerifier);
    }//  w  w w .  j a  v  a  2 s  .com
    if (httpAuthBase64 != null) {
        connection.setRequestProperty("Authorization", new StringBuffer(httpAuthBase64.length() + 6)
                .append("Basic ").append(httpAuthBase64).toString());
    }
    connection.setRequestProperty("Content-Type", "text/plain; charset=\"utf8\"");
    connection.setRequestMethod("GET");

    int returnCode = connection.getResponseCode();
    InputStream connectionIn = null;
    if (returnCode == 200) {
        connectionIn = connection.getInputStream();
    } else {
        connectionIn = connection.getErrorStream();
    }
    BufferedReader buffer = new BufferedReader(new InputStreamReader(connectionIn));
    String inputLine;
    while ((inputLine = buffer.readLine()) != null) {
        sb.append(inputLine);
    }
    buffer.close();

    return sb.toString();
}

From source file:com.pubkit.network.PubKitNetwork.java

public static JSONObject sendPost(String apiKey, JSONObject jsonObject) {
    URL url;//from www . j a  va 2s  .c o m
    HttpURLConnection connection = null;
    try {
        //Create connection
        url = new URL(PUBKIT_API_URL);
        String encodedData = jsonObject.toString();
        byte[] postDataBytes = jsonObject.toString().getBytes("UTF-8");

        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Content-Length", "" + String.valueOf(postDataBytes.length));
        connection.setRequestProperty("api_key", apiKey);

        connection.setUseCaches(false);
        connection.setDoOutput(true);

        //Send request
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(encodedData);//set data
        wr.flush();

        //Get Response
        InputStream inputStream = connection.getErrorStream(); //first check for error.
        if (inputStream == null) {
            inputStream = connection.getInputStream();
        }
        BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));

        String line;
        StringBuilder response = new StringBuilder();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        wr.close();
        rd.close();

        String responseString = response.toString();
        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            return new JSONObject("{'error':'" + responseString + "'}");
        } else {
            try {
                return new JSONObject(responseString);
            } catch (JSONException e) {
                Log.e("PUBKIT", "Error parsing data", e);
            }
        }
    } catch (Exception e) {
        Log.e("PUBKIT", "Network exception:", e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
    return null;
}