Example usage for java.net URLConnection getOutputStream

List of usage examples for java.net URLConnection getOutputStream

Introduction

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

Prototype

public OutputStream getOutputStream() throws IOException 

Source Link

Document

Returns an output stream that writes to this connection.

Usage

From source file:org.sleeksnap.uploaders.url.GoogleShortener.java

@Override
public String upload(final URLUpload url) throws Exception {
    // Sanity check, otherwise google's api returns a 400
    if (url.toString().matches("http://goo.gl/[a-zA-Z0-9]{1,10}")) {
        return url.toString();
    }/*w ww  .  j  av a 2 s  . c  om*/

    final URLConnection connection = new URL(PAGE_URL).openConnection();
    connection.setDoOutput(true);
    connection.setRequestProperty("Content-type", "application/json");

    final JSONObject out = new JSONObject();

    out.put("longUrl", url.getURL());

    final OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
    writer.write(out.toString());
    writer.flush();
    writer.close();

    final String contents = StreamUtils.readContents(connection.getInputStream());

    final JSONObject resp = new JSONObject(contents);

    if (resp.has("id")) {
        return resp.getString("id");
    } else {
        throw new UploadException("Unable to find short url");
    }
}

From source file:service.GoogleCalendarAuth.java

public GoogleCalendarAuth(String client_id, String key) {
    final long now = System.currentTimeMillis() / 1000L;
    final long exp = now + 3600;
    final char[] password = "notasecret".toCharArray();
    final String claim = "{\"iss\":\"" + client_id + "\"," + "\"scope\":\"" + SCOPE + "\","
            + "\"aud\":\"https://accounts.google.com/o/oauth2/token\"," + "\"exp\":" + exp + "," +
            // "\"prn\":\"some.user@somecorp.com\"," + // This require some.user to have their email served from a googlemail domain?
            "\"iat\":" + now + "}";
    try {//  w  w  w  . j  av  a  2 s.  c om
        final String jwt = Base64.encodeBase64URLSafeString(jwt_header.getBytes()) + "."
                + Base64.encodeBase64URLSafeString(claim.getBytes("UTF-8"));
        final byte[] jwt_data = jwt.getBytes("UTF8");
        final Signature sig = Signature.getInstance("SHA256WithRSA");

        final KeyStore ks = java.security.KeyStore.getInstance("PKCS12");
        ks.load(new FileInputStream(key), password);

        sig.initSign((PrivateKey) ks.getKey("privatekey", password));
        sig.update(jwt_data);
        final byte[] signatureBytes = sig.sign();
        final String b64sig = Base64.encodeBase64URLSafeString(signatureBytes);

        final String assertion = jwt + "." + b64sig;
        //System.out.println("Assertion: " + assertion);
        final String data = "grant_type=assertion" + "&assertion_type="
                + URLEncoder.encode("http://oauth.net/grant_type/jwt/1.0/bearer", "UTF-8") + "&assertion="
                + URLEncoder.encode(assertion, "UTF-8");

        // Make the Access Token Request
        URLConnection conn = null;
        try {
            final URL url = new URL("https://accounts.google.com/o/oauth2/token");
            conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(data);
            wr.flush();

            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                if (line.split(":").length > 0)
                    if (line.split(":")[0].trim().equals("\"access_token\""))
                        access_token = line.split(":")[1].trim().replace("\"", "").replace(",", "");
                System.out.println(line);
            }
            wr.close();
            rd.close();
        } catch (Exception ex) {
            final InputStream error = ((HttpURLConnection) conn).getErrorStream();
            final BufferedReader br = new BufferedReader(new InputStreamReader(error));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null)
                sb.append(line);
            System.out.println("Error: " + ex + "\n " + sb.toString());
        }
        System.out.println("access_token=" + access_token);
    } catch (Exception ex) {
        System.out.println("Error: " + ex);
    }
}

From source file:com.support.android.designlibdemo.DetailContactActivity.java

public String postData(String sURL, String sData) {
    try {//from   w  w  w. j av a  2  s  . c  o  m
        String data = URLEncoder.encode("jsonString", "UTF-8") + "=" + URLEncoder.encode(sData, "UTF-8");
        URL url = new URL(sURL);
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data);
        wr.flush();

        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line = null;

        while ((line = reader.readLine()) != null) {

            sb.append(line + "\n");
        }

        return sb.toString();

    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}

From source file:ca.etsmtl.applets.etsmobile.api.SignetBackgroundThread.java

@SuppressWarnings("unchecked")
public T fetchObject() {
    T object = null;// w w  w  .  j a  v  a2  s. co  m

    try {
        final StringBuilder sb = new StringBuilder();
        sb.append(urlStr);
        sb.append("/");
        sb.append(action);

        final Gson gson = new Gson();
        final String bodyParamsString = gson.toJson(bodyParams);

        final URL url = new URL(sb.toString());
        final URLConnection conn = url.openConnection();
        conn.addRequestProperty("Content-Type", "application/json; charset=UTF-8");

        conn.setDoOutput(true);
        final OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(bodyParamsString);
        wr.flush();

        final StringWriter writer = new StringWriter();
        final InputStream in = conn.getInputStream();
        IOUtils.copy(in, writer);
        in.close();
        wr.close();

        final String jsonString = writer.toString();

        JSONObject jsonObject;
        jsonObject = new JSONObject(jsonString);

        JSONObject jsonRootArray;
        jsonRootArray = jsonObject.getJSONObject("d");
        object = (T) gson.fromJson(jsonRootArray.toString(), typeOfClass);
        android.util.Log.d("JSON", jsonRootArray.toString());
    } catch (final MalformedURLException e) {
        e.printStackTrace();
    } catch (final IOException e) {
        e.printStackTrace();
    } catch (final JSONException e) {
        e.printStackTrace();
    }
    return object;
}

From source file:com.github.reverseproxy.ReverseProxyJettyHandler.java

private void setDoOutput(String method, String requestBody, URLConnection urlConnection) throws IOException {
    if (method.equalsIgnoreCase("POST") || method.equalsIgnoreCase("PUT")) {
        urlConnection.setDoOutput(true);
        if (!StringUtils.isEmpty(requestBody)) {
            IOUtils.write(requestBody, urlConnection.getOutputStream());
        }/*w  w w  .  j  av  a  2  s  . c o m*/
    } else {
        urlConnection.setDoOutput(false);
    }
}

From source file:org.apache.jcs.auxiliary.lateral.http.remove.DeleteLateralCacheUnicaster.java

/** Description of the Method */
public void callClearCache(String ccServletURL) {
    URL clear;/*from   ww w. ja  v  a2  s. c om*/
    URLConnection clearCon;
    InputStream in;
    OutputStream out;
    try {
        clear = new URL(ccServletURL);
        clearCon = clear.openConnection();
        clearCon.setDoOutput(true);
        clearCon.setDoInput(true);
        //clearCon.connect();
        out = clearCon.getOutputStream();
        in = clearCon.getInputStream();
        int cur = in.read();
        while (cur != -1) {
            cur = in.read();
        }
        out.close();
        in.close();
        // System.out.println("closed inputstream" );
    } catch (Exception e) {
        log.error(e);
    } finally {
        //in.close();
        out = null;
        in = null;
        clearCon = null;
        clear = null;
        log.info("called clear cache for " + ccServletURL);
        return;
    }
}

From source file:monitoring.tools.GooglePlayAPI.java

protected void generateNewAccessToken() throws MalformedURLException, IOException {

    String query = "grant_type=refresh_token" + "&client_id=" + clientID + "&client_secret=" + clientSecret
            + "&refresh_token=" + refreshToken;
    URLConnection httpConnection = new URL(tokenUri + "?" + query).openConnection();
    httpConnection.setDoOutput(true);// w ww .  ja va 2 s  .com
    //httpConnection.setFixedLengthStreamingMode(0);
    try (OutputStream output = httpConnection.getOutputStream()) {
        output.write(query.getBytes("UTF-8"));
    }
    JSONObject res = new JSONObject(Utils.streamToString(httpConnection.getInputStream()));
    accessToken = res.getString("access_token");

}

From source file:edu.csh.coursebrowser.CourseActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_course);
    // Show the Up button in the action bar.
    this.getActionBar().setHomeButtonEnabled(false);
    map_item = new HashMap<String, Course>();
    map = new ArrayList<String>();
    Bundle args = this.getIntent().getExtras();
    this.setTitle(args.getCharSequence("title"));
    try {/*from  w ww .ja  va  2s. c o  m*/
        JSONObject jso = new JSONObject(args.get("args").toString());
        JSONArray jsa = new JSONArray(jso.getString("courses"));
        ListView lv = (ListView) this.findViewById(R.id.course_list);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, map);
        for (int i = 0; i < jsa.length(); ++i) {
            String s = jsa.getString(i);
            JSONObject obj = new JSONObject(s);
            Course course = new Course(obj.getString("title"), obj.getString("department"),
                    obj.getString("course"), obj.getString("description"), obj.getString("id"));
            addItem(course);
            Log.v("Added", course.toString());
        }
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                String s = ((TextView) arg1).getText().toString();
                final Course course = map_item.get(s);
                new AsyncTask<String, String, String>() {
                    ProgressDialog p;

                    protected void onPreExecute() {
                        p = new ProgressDialog(CourseActivity.this);
                        p.setTitle("Fetching Info");
                        p.setMessage("Contacting Server...");
                        p.setCancelable(false);
                        p.show();
                    }

                    protected String doInBackground(String... dep) {
                        String params = "action=getSections&course=" + course.id;
                        Log.v("Params", params);
                        URL url;
                        String back = "";
                        try {
                            url = new URL("http://iota.csh.rit" + ".edu/schedule/js/browseAjax" + ".php");

                            URLConnection conn = url.openConnection();
                            conn.setDoOutput(true);
                            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
                            writer.write(params);
                            writer.flush();
                            String line;
                            BufferedReader reader = new BufferedReader(
                                    new InputStreamReader(conn.getInputStream()));

                            while ((line = reader.readLine()) != null) {
                                Log.v("Back:", line);
                                back += line;
                            }
                            writer.close();
                            reader.close();
                        } catch (MalformedURLException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                            return null;
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                            p.dismiss();
                            return null;
                        }
                        return back;
                    }

                    protected void onPostExecute(String s) {
                        if (s == null || s == "") {
                            new AlertError(CourseActivity.this, "IO Error!").show();
                            return;
                        }
                        try {
                            JSONObject jso = new JSONObject(s);
                            JSONArray jsa = new JSONArray(jso.getString("sections"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                            new AlertError(CourseActivity.this, "Invalid JSON From Server").show();
                            p.dismiss();
                            return;
                        }
                        Intent intent = new Intent(CourseActivity.this, SectionsActivity.class);
                        intent.putExtra("title", course.title);
                        intent.putExtra("id", course.id);
                        intent.putExtra("description", course.description);
                        intent.putExtra("args", s);
                        startActivity(intent);
                        p.dismiss();
                    }
                }.execute(course.id);
            }

        });

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        new AlertError(this, "Invalid JSON");
        e.printStackTrace();
    }

}

From source file:com.linkedin.pinot.controller.helix.ControllerTest.java

public JSONObject postQuery(String query, String brokerBaseApiUrl) throws Exception {
    final JSONObject json = new JSONObject();
    json.put("pql", query);
    json.put("trace", isTraceEnabled);
    //    json.put("debugOptions", "routingOptions=FORCE_LLC,FORCE_HLC;otherOption=foo,bar");

    final long start = System.currentTimeMillis();
    final URLConnection conn = new URL(brokerBaseApiUrl + "/query").openConnection();
    conn.setDoOutput(true);//from   www.j a  va  2  s . co  m
    final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
    final String reqStr = json.toString();

    writer.write(reqStr, 0, reqStr.length());
    writer.flush();

    JSONObject ret = getBrokerReturnJson(conn);
    final long stop = System.currentTimeMillis();

    LOGGER.debug("Time taken for '{}':{}ms", query, (stop - start));
    return ret;
}

From source file:edu.csh.coursebrowser.DepartmentActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_departments);
    // Show the Up button in the action bar.
    // getActionBar().setDisplayHomeAsUpEnabled(false);
    this.getActionBar().setHomeButtonEnabled(true);
    final Bundle b = this.getIntent().getExtras();
    map_item = new HashMap<String, Department>();
    map = new ArrayList<String>();
    Bundle args = this.getIntent().getExtras();
    this.setTitle(args.getCharSequence("from"));
    try {/*  www .  j a v  a 2  s.  co m*/
        JSONObject jso = new JSONObject(args.get("args").toString());
        JSONArray jsa = new JSONArray(jso.getString("departments"));
        ListView lv = (ListView) this.findViewById(R.id.department_list);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, map);
        for (int i = 0; i < jsa.length(); ++i) {
            String s = jsa.getString(i);
            JSONObject obj = new JSONObject(s);
            Department dept = new Department(obj.getString("title"), obj.getString("id"),
                    obj.getString("code"));
            addItem(dept);
            Log.v("Added", dept.toString());
        }
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                String s = ((TextView) arg1).getText().toString();
                final Department department = map_item.get(s);
                new AsyncTask<String, String, String>() {
                    ProgressDialog p;

                    protected void onPreExecute() {
                        p = new ProgressDialog(DepartmentActivity.this);
                        p.setTitle("Fetching Info");
                        p.setMessage("Contacting Server...");
                        p.setCancelable(false);
                        p.show();
                    }

                    protected String doInBackground(String... dep) {
                        String params = "action=getCourses&department=" + dep[0] + "&quarter="
                                + b.getString("qCode");
                        Log.v("Params", params);
                        URL url;
                        String back = "";
                        try {
                            url = new URL("http://iota.csh.rit" + ".edu/schedule/js/browseAjax" + ".php");

                            URLConnection conn = url.openConnection();
                            conn.setDoOutput(true);
                            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
                            writer.write(params);
                            writer.flush();
                            String line;
                            BufferedReader reader = new BufferedReader(
                                    new InputStreamReader(conn.getInputStream()));

                            while ((line = reader.readLine()) != null) {
                                Log.v("Back:", line);
                                back += line;
                            }
                            writer.close();
                            reader.close();
                        } catch (MalformedURLException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                            return null;
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                            p.dismiss();
                            return null;
                        }
                        return back;
                    }

                    protected void onPostExecute(String s) {
                        if (s == null || s == "") {
                            new AlertError(DepartmentActivity.this, "IO Error!").show();
                            return;
                        }

                        try {
                            JSONObject jso = new JSONObject(s);
                            JSONArray jsa = new JSONArray(jso.getString("courses"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                            new AlertError(DepartmentActivity.this, "Invalid JSON From Server").show();
                            p.dismiss();
                            return;
                        }
                        Intent intent = new Intent(DepartmentActivity.this, CourseActivity.class);
                        intent.putExtra("title", department.title);
                        intent.putExtra("id", department.id);
                        intent.putExtra("code", department.code);
                        intent.putExtra("args", s);
                        startActivity(intent);
                        p.dismiss();
                    }
                }.execute(department.id);
            }

        });

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        new AlertError(this, "Invalid JSON");
        e.printStackTrace();
    }

}