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.memetix.mst.MicrosoftTranslatorAPI.java

/**
 * Forms an HTTP request, sends it using GET method and returns the result of the request as a String.
 * /*from   w  ww  .ja v  a  2  s. co  m*/
 * @param url The URL to query for a String response.
 * @return The translated String.
 * @throws Exception on error.
 */
private static String retrieveResponse(final URL url) throws Exception {
    if (clientId != null && clientSecret != null && System.currentTimeMillis() > tokenExpiration) {
        String tokenJson = getToken(clientId, clientSecret);
        Integer expiresIn = Integer
                .parseInt((String) ((JSONObject) JSONValue.parse(tokenJson)).get("expires_in"));
        tokenExpiration = System.currentTimeMillis() + ((expiresIn * 1000) - 1);
        token = "Bearer " + (String) ((JSONObject) JSONValue.parse(tokenJson)).get("access_token");
    }
    final HttpURLConnection uc = (HttpURLConnection) url.openConnection();
    if (referrer != null)
        uc.setRequestProperty("referer", referrer);
    uc.setRequestProperty("Content-Type", contentType + "; charset=" + ENCODING);
    uc.setRequestProperty("Accept-Charset", ENCODING);
    if (token != null) {
        uc.setRequestProperty("Authorization", token);
    }
    uc.setRequestMethod("GET");
    uc.setDoOutput(true);

    try {
        final int responseCode = uc.getResponseCode();
        final String result = inputStreamToString(uc.getInputStream());
        if (responseCode != 200) {
            throw new Exception("Error from Microsoft Translator API: " + result);
        }
        return result;
    } finally {
        if (uc != null) {
            uc.disconnect();
        }
    }
}

From source file:Main.java

public static byte[] doGet(String urlStr) {
    URL url = null;/*from w  w  w  .j a  v a 2  s  .co m*/
    HttpURLConnection conn = null;
    InputStream is = null;
    ByteArrayOutputStream baos = null;
    try {
        url = new URL(urlStr);
        conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
        conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
        conn.setRequestMethod("GET");
        conn.setRequestProperty("accept", "*/*");
        conn.setRequestProperty("connection", "Keep-Alive");
        if (conn.getResponseCode() == 200) {
            is = conn.getInputStream();
            baos = new ByteArrayOutputStream();
            int len = -1;
            byte[] buf = new byte[128];

            while ((len = is.read(buf)) != -1) {
                baos.write(buf, 0, len);
            }
            baos.flush();
            return baos.toByteArray();
        } else {
            throw new RuntimeException(" responseCode is not 200 ... ");
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (is != null)
                is.close();
        } catch (IOException e) {
        }
        try {
            if (baos != null)
                baos.close();
        } catch (IOException e) {
        }
        conn.disconnect();
    }

    return null;

}

From source file:net.dian1.player.download.DownloadTask.java

public static Boolean downloadFile(DownloadJob job) throws IOException {

    // TODO rewrite to apache client

    PlaylistEntry mPlaylistEntry = job.getPlaylistEntry();
    String mDestination = job.getDestination();

    Music engineMusic = mPlaylistEntry.getMusic();
    String url = engineMusic.getFirstMusicNetUrl();

    if (TextUtils.isEmpty(url)) {
        engineMusic = requestMusicDetail(engineMusic.getId());
        url = engineMusic.getFirstMusicNetUrl();
        job.getPlaylistEntry().setMusic(engineMusic);
    }//ww  w. j  ava2  s .co  m

    //url = "http://room2.5dian1.net/??1/15.?.mp3";
    if (TextUtils.isEmpty(url)) {
        return false;
    }
    URL u = new URL(url);
    HttpURLConnection connection = (HttpURLConnection) u.openConnection();
    connection.setRequestMethod("GET");
    //c.setDoOutput(true);
    //c.setDoInput(true);
    connection.setRequestProperty("Accept", "*/*");
    connection.setRequestProperty("Content-Type", "audio/mpeg");
    connection.connect();
    job.setTotalSize(connection.getContentLength());

    Log.i(Dian1Application.TAG, "creating file");

    String path = DownloadHelper.getAbsolutePath(mPlaylistEntry, mDestination);
    String fileName = DownloadHelper.getFileName(mPlaylistEntry, job.getFormat());

    try {
        // Create multiple directory
        boolean success = (new File(path)).mkdirs();
        if (success) {
            Log.i(Dian1Application.TAG, "Directory: " + path + " created");
        }

    } catch (Exception e) {//Catch exception if any
        Log.e(Dian1Application.TAG, "Error creating folder", e);
        return false;
    }

    File outFile = new File(path, fileName);

    FileOutputStream fos = new FileOutputStream(outFile);

    InputStream in = connection.getInputStream();

    if (in == null) {
        // When InputStream is a NULL
        fos.close();
        return false;
    }

    byte[] buffer = new byte[1024];
    int lenght = 0;
    while ((lenght = in.read(buffer)) > 0) {
        fos.write(buffer, 0, lenght);
        job.setDownloadedSize(job.getDownloadedSize() + lenght);
    }
    fos.close();

    mPlaylistEntry.getMusic().getFirstMusicUrlInfo().setLocalUrl(outFile.getAbsolutePath());
    //downloadCover(job);
    return true;
}

From source file:com.google.android.gcm.demo.app.ServerUtilities.java

/**
 * Issue a POST request to the server.//from   w w w.j  a  v a2s .  c  om
 *
 * @param endpoint POST address.
 * @param params request parameters.
 *
 * @throws IOException propagated from POST.
 */
private static void post(String endpoint, Map<String, String> params) throws IOException {
    URL url;
    try {
        url = new URL(endpoint);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("invalid url: " + endpoint);
    }
    JSONObject jsonObj = new JSONObject(params);
    String body = jsonObj.toString();
    Log.v(TAG, "Posting '" + body + "' to " + url);
    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", "application/json");
        // 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);
        }
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:com.thyn.backend.gcm.GcmSender.java

public static String sendMessageToDeviceGroup(String to, String message, String sender, Long profileID,
        Long taskID) {/*  w w  w.  ja  va2s .c  o m*/
    String resp = null;
    try {
        // Prepare JSON containing the GCM message content. What to send and where to send.
        JSONObject jGcmData = new JSONObject();
        JSONObject jData = new JSONObject();
        jData.put("message", message);
        jData.put("sender", sender);
        jData.put("profileID", profileID);
        jData.put("taskID", taskID);
        // Where to send GCM message.
        if (to != null && message != null) {
            jGcmData.put("to", to.trim());
        } else {
            Logger.logError("Error", new NullPointerException());
            return null;
        }
        // What to send in GCM message.
        jGcmData.put("data", jData);

        // Create connection to send GCM Message request.
        URL url = new URL("https://gcm-http.googleapis.com/gcm/send");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Authorization", "key=" + API_KEY);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);

        System.out.println("The payload is: " + jGcmData.toString());
        // Send GCM message content.
        OutputStream outputStream = conn.getOutputStream();
        outputStream.write(jGcmData.toString().getBytes());

        // Read GCM response.
        InputStream inputStream = conn.getInputStream();
        resp = IOUtils.toString(inputStream);

        if (resp == null || resp.trim().equals("")) {
            System.out.println("Got a Null Response from the server. Unable to send GCM message.");
            return null;
        } else {
            System.out.println("the response from GCM server is: " + resp);
            System.out.println("Check your device/emulator for notification or logcat for "
                    + "confirmation of the receipt of the GCM message.");
        }
        JSONObject jResp = null;
        try {
            jResp = new JSONObject(resp);
        } catch (JSONException jsone) {
            jsone.printStackTrace();
        }
        int rSuccess = jResp.getInt("success");
        int rFailure = jResp.getInt("failure");
        if (rSuccess == 0 && rFailure > 0)
            System.out.println(
                    "Failed sending message to the recipient. Total no. of devices for the user. " + rFailure);
        else if (rSuccess > 0 && rFailure == 0)
            System.out.println("Success sending message to all receipients. Total no. of devices for the user "
                    + rSuccess);
        else
            System.out.println("Partial success. Success sending to " + rSuccess
                    + " devices. And failed sending to " + rFailure + " devices");
    } catch (IOException e) {
        Logger.logError("Unable to send GCM message.", e);
    }

    return resp;
}

From source file:com.example.scandevice.MainActivity.java

public static String excutePost(String targetURL, String urlParameters) {
    URL url;/*from w w w  .j  av  a  2  s  .c om*/
    HttpURLConnection connection = null;
    try {
        //Create connection
        url = new URL(targetURL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("charset", "utf-8");

        connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
        connection.setRequestProperty("Content-Language", "en-US");

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

        //Send request
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

    } catch (Exception e) {
        e.printStackTrace();
        return "Don't post data";

    } finally {

        if (connection != null) {
            connection.disconnect();
        }
    }
    return "Data Sent";
}

From source file:com.screenslicer.core.util.Email.java

public static void sendResults(EmailExport export) {
    if (WebApp.DEV) {
        return;/* w ww  . ja  v a 2  s.c o m*/
    }
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("key", Config.instance.mandrillKey());
    List<Map<String, String>> to = new ArrayList<Map<String, String>>();
    for (int i = 0; i < export.recipients.length; i++) {
        to.add(CommonUtil.asMap("email", "name", "type", export.recipients[i],
                export.recipients[i].split("@")[0], "to"));
    }
    List<Map<String, String>> attachments = new ArrayList<Map<String, String>>();
    for (Map.Entry<String, byte[]> entry : export.attachments.entrySet()) {
        attachments.add(CommonUtil.asMap("type", "name", "content", new Tika().detect(entry.getValue()),
                entry.getKey(), Base64.encodeBase64String(entry.getValue())));
    }
    params.put("message", CommonUtil.asObjMap("track_clicks", "track_opens", "html", "text", "headers",
            "subject", "from_email", "from_name", "to", "attachments", false, false, "Results attached.",
            "Results attached.", CommonUtil.asMap("Reply-To", Config.instance.mandrillEmail()), export.title,
            Config.instance.mandrillEmail(), Config.instance.mandrillEmail(), to, attachments));
    params.put("async", true);
    HttpURLConnection conn = null;
    String resp = null;
    Log.info("Sending email: " + export.title, false);
    try {
        conn = (HttpURLConnection) new URL("https://mandrillapp.com/api/1.0/messages/send.json")
                .openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("User-Agent", "Mandrill-Curl/1.0");
        String data = CommonUtil.gson.toJson(params, CommonUtil.objectType);
        byte[] bytes = data.getBytes("utf-8");
        conn.setRequestProperty("Content-Length", "" + bytes.length);
        OutputStream os = conn.getOutputStream();
        os.write(bytes);
        conn.connect();
        resp = IOUtils.toString(conn.getInputStream(), "utf-8");
        if (resp.contains("\"rejected\"") || resp.contains("\"invalid\"")) {
            Log.warn("Invalid/rejected email addreses");
        }
    } catch (Exception e) {
        Log.exception(e);
    }
}

From source file:de.mas.telegramircbot.utils.images.ImgurUploader.java

public static String uploadImageAndGetLink(String clientID, byte[] image) throws IOException {
    URL url;/*from   w w w.  ja v  a 2s . c  o m*/
    url = new URL(Settings.IMGUR_API_URL);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    String dataImage = Base64.getEncoder().encodeToString(image);
    String data = URLEncoder.encode("image", "UTF-8") + "=" + URLEncoder.encode(dataImage, "UTF-8");

    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Authorization", "Client-ID " + clientID);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    conn.connect();
    StringBuilder stb = new StringBuilder();
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();

    // Get the response
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;
    while ((line = rd.readLine()) != null) {
        stb.append(line).append("\n");
    }
    wr.close();
    rd.close();

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(ImgurResponse.class, new ImgurResponseDeserializer());
    Gson gson = gsonBuilder.create();

    // The JSON data
    try {
        ImgurResponse response = gson.fromJson(stb.toString(), ImgurResponse.class);
        return response.getLink();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return stb.toString();
}

From source file:com.murrayc.galaxyzoo.app.provider.client.ZooniverseClient.java

private static void setConnectionUserAgent(final HttpURLConnection connection) {
    connection.setRequestProperty(HttpUtils.HTTP_REQUEST_HEADER_PARAM_USER_AGENT, HttpUtils.USER_AGENT_MURRAYC);
}

From source file:com.surfs.storage.common.util.HttpUtils.java

public static String invokeHttpForGet(String path, String... agrs) throws IOException {
    URL url = new URL(path);
    LogFactory.info("rest url:" + url.toString());
    HttpURLConnection con = null;
    try {//  ww w.j  a v  a 2s. c  om
        con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.setConnectTimeout(10000);
        con.setReadTimeout(1000 * 60 * 30);
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setUseCaches(false);

        for (String string : agrs) {
            con.setRequestProperty("Content-type", "application/json");
            con.setRequestMethod("POST");
            OutputStream out = con.getOutputStream();
            out.write(string.getBytes("UTF-8"));
        }

        if (con.getResponseCode() != 200)
            throw new ConnectException(con.getResponseMessage());

        InputStream is = con.getInputStream();

        return readResponse(is);

    } catch (IOException e) {
        throw e;
    } finally {
        if (con != null) {
            con.disconnect();
        }
    }
}