Example usage for java.net URLConnection setDoOutput

List of usage examples for java.net URLConnection setDoOutput

Introduction

In this page you can find the example usage for java.net URLConnection 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:de.uzk.hki.da.repository.ElasticsearchMetadataIndex.java

@Override
public String getIndexedMetadata(String indexName, String objectId) {

    try {/*  www . ja  v  a2  s. c o m*/
        String requestURL = "http://localhost:9200/" + indexName + "/" + C.ORE_AGGREGATION + "/_search?q=_id:"
                + objectId + "*";
        System.out.println("requestURL:" + requestURL);
        logger.debug("requestURL:" + requestURL);
        URL wikiRequest;
        wikiRequest = new URL(requestURL);
        URLConnection connection;
        connection = wikiRequest.openConnection();
        connection.setDoOutput(true);

        Scanner scanner;
        scanner = new Scanner(wikiRequest.openStream());
        String response = scanner.useDelimiter("\\Z").next();
        System.out.println("R:" + response);

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

From source file:de.uzk.hki.da.repository.ElasticsearchMetadataIndex.java

@Override
public String getAllIndexedMetadataFromIdSubstring(String indexName, String objectId) {

    try {//from ww w.j a va2s .com
        String requestURL = "http://localhost:9200/" + indexName + "/" + C.ORE_AGGREGATION + "/_search?q=_id:"
                + objectId + "" + "*";
        System.out.println("requestURL:" + requestURL);
        logger.debug("requestURL:" + requestURL);
        URL wikiRequest;
        wikiRequest = new URL(requestURL);
        URLConnection connection;
        connection = wikiRequest.openConnection();
        connection.setDoOutput(true);

        Scanner scanner;
        scanner = new Scanner(wikiRequest.openStream());
        String response = scanner.useDelimiter("\\Z").next();
        System.out.println("R:" + response);

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

From source file:fr.free.divde.webcam.WebcamApplet.java

public void sendImage(JSObject parameters) {
    final String url = (String) parameters.getMember("url");
    final String format = (String) getJSProperty(parameters, "format", "png");
    final Map<String, Object> headers = getJSMapProperty(parameters, "headers");
    final JSObject callback = (JSObject) getJSProperty(parameters, "callback", null);
    imageCapture.captureImage(new ImageListener() {
        @Override//from www.jav a  2 s. com
        public void nextFrame(BufferedImage image) {
            try {
                URL urlObject = new URL(getDocumentBase(), url);
                URLConnection connection = urlObject.openConnection();
                connection.setDoOutput(true);
                setHeaders(connection, headers);
                if (connection.getRequestProperty("content-type") == null) {
                    // default content type
                    connection.setRequestProperty("content-type", "image/" + format);
                }
                OutputStream out = connection.getOutputStream();
                ImageIO.write(image, format, out);
                out.flush();
                out.close();
                if (callback != null) {
                    StringWriter response = new StringWriter();
                    IOUtils.copy(connection.getInputStream(), response, "UTF-8");
                    callJS(callback, response.toString());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

From source file:game.Clue.JerseyClient.java

public void requestLogintoServer(String name) {

    try {//from   w w w  .j  a  va2s .  c  om
        for (int i = 0; i < 6; i++) {
            JSONObject jsonObject = new JSONObject(name);

            URL url = new URL(
                    "http://ec2-54-165-198-60.compute-1.amazonaws.com:8080/CluelessServer/webresources/service/player"
                            + i);
            URLConnection connection = url.openConnection();
            connection.setDoOutput(true);
            //setDoOutput(true);
            connection.setRequestProperty("PUT", "application/json");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);

            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
            out.write(jsonObject.toString());

            System.out.println("Sent PUT message for logging into server");
            out.close();
        }
    } catch (Exception e) {
        e.printStackTrace();

    }

}

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 {//from w  w w. j a v  a2 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();
    }

}

From source file:org.spoutcraft.launcher.util.Download.java

@SuppressWarnings("unused")
public void run() {
    ReadableByteChannel rbc = null;
    FileOutputStream fos = null;/*from  ww w  . jav  a  2  s. co m*/
    try {
        URLConnection conn = url.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(false);
        System.setProperty("http.agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");
        conn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19");
        HttpURLConnection.setFollowRedirects(true);
        conn.setUseCaches(false);
        ((HttpURLConnection) conn).setInstanceFollowRedirects(true);
        int response = ((HttpURLConnection) conn).getResponseCode();
        InputStream in = getConnectionInputStream(conn);

        size = conn.getContentLength();
        outFile = new File(outPath);
        outFile.delete();

        rbc = Channels.newChannel(in);
        fos = new FileOutputStream(outFile);

        stateChanged();

        Thread progress = new MonitorThread(Thread.currentThread(), rbc);
        progress.start();

        fos.getChannel().transferFrom(rbc, 0, size > 0 ? size : Integer.MAX_VALUE);
        in.close();
        rbc.close();
        progress.interrupt();
        if (size > 0) {
            if (size == outFile.length()) {
                result = Result.SUCCESS;
            }
        } else {
            result = Result.SUCCESS;
        }
    } catch (PermissionDeniedException e) {
        exception = e;
        result = Result.PERMISSION_DENIED;
    } catch (DownloadException e) {
        exception = e;
        result = Result.FAILURE;
    } catch (Exception e) {
        exception = e;
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(fos);
        IOUtils.closeQuietly(rbc);
    }
}

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);
    final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
    final String reqStr = json.toString();

    writer.write(reqStr, 0, reqStr.length());
    writer.flush();//ww  w.j  a  v a2s. co  m

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

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

From source file:org.jlibrary.core.http.client.HTTPDelegate.java

/**
 * Excecutes a void request/*from  w  w  w  . j  a  v  a 2  s.co m*/
 * 
 * @param methodName Name of the method to execute
 * @param params Method params
 * @param returnClass Class for the return object. If the class is InputStream this method will return 
 * the HTTP request input stream
 * @param inputStream Stream for reading contents that will be sent
 * 
 * @throws Exception If there is any problem running the request
 */
public Object doRequest(String methodName, Object[] params, Class returnClass, InputStream inputStream)
        throws Exception {

    try {
        logger.debug(servletURL.toString());
        logger.debug("opening connection");
        URLConnection conn = servletURL.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);
        conn.setRequestProperty("Content-type", "text/plain");

        //write request and params:
        OutputStream stream = conn.getOutputStream();
        // write streaming header if necessary
        if (inputStream != null) {
            stream.write(ByteUtils.intToByteArray("stream-input".getBytes().length));
            stream.write("stream-input".getBytes());
            stream.flush();
        }
        if (returnClass == InputStream.class) {
            stream.write(ByteUtils.intToByteArray("stream-output".getBytes().length));
            stream.write("stream-output".getBytes());
            stream.flush();
        }

        // Write method
        stream.write(ByteUtils.intToByteArray(methodName.getBytes().length));
        stream.write(methodName.getBytes());
        //stream.flush();
        // Write parameters
        stream.write(ByteUtils.intToByteArray(params.length));
        for (int i = 0; i < params.length; i++) {
            byte[] content = SerializationUtils.serialize((Serializable) params[i]);
            stream.write(ByteUtils.intToByteArray(content.length));
            stream.write(content);
            stream.flush();
        }

        if (inputStream != null) {
            IOUtils.copy(inputStream, stream);
        }

        //stream.flush();
        //stream.close();

        //read response:
        InputStream input = conn.getInputStream();
        if (returnClass == InputStream.class) {
            // Contents will be read from outside
            return input;
        }
        ObjectInputStream objInput = new ObjectInputStream(input);
        Object o = objInput.readObject();
        if (o == null) {
            return null;
        }
        stream.close();
        if (o instanceof Exception) {
            throw (Exception) o;
        } else {
            if (returnClass == null) {
                return null;
            }
            // try to cast
            try {
                returnClass.cast(o);
            } catch (ClassCastException cce) {
                String msg = "Unexpected response from execution servlet: " + o;
                logger.error(msg);
                throw new Exception(msg);
            }
        }
        return o;
    } catch (ClassNotFoundException e) {
        throw new Exception(e);
    } catch (ClassCastException e) {
        throw new Exception(e);
    } catch (IOException e) {
        throw new Exception(e);
    }
}

From source file:com.gmail.tracebachi.DeltaSkins.Shared.MojangApi.java

private HttpURLConnection openNameToIdConnection() throws IOException {
    URL url = new URL(NAMES_TO_IDS_ADDR);
    URLConnection connection = url.openConnection();
    connection.setConnectTimeout(CONNECT_TIMEOUT);
    connection.setReadTimeout(READ_TIMEOUT);
    connection.setDoInput(true);//  w w  w.ja v a 2s.c o m
    connection.setDoOutput(true);
    connection.setUseCaches(false);
    return (HttpURLConnection) connection;
}

From source file:com.openkm.extension.servlet.ZohoServlet.java

@Override
public String getTicket() throws OKMException {
    log.debug("getTicket()");
    updateSessionManager();//w  w w .  j  av  a2 s.  c om
    String ticket = "";

    try {
        // Construct data
        // String data = URLEncoder.encode("LOGIN_ID", "UTF-8") + "=" + URLEncoder.encode(Config.ZOHO_USER, "UTF-8");
        // data += "&" + URLEncoder.encode("PASSWORD", "UTF-8") + "=" + URLEncoder.encode(Config.ZOHO_PASSWORD, "UTF-8");
        // data += "&" + URLEncoder.encode("FROM_AGENT", "UTF-8") + "=" + URLEncoder.encode("true", "UTF-8");
        // data += "&" + URLEncoder.encode("servicename", "UTF-8") + "=" + URLEncoder.encode("ZohoWriter", "UTF-8");

        // Send data
        URL url;
        url = new URL("https://accounts.zoho.com/login");
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);

        // Get the response
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;

        while ((line = rd.readLine()) != null) {
            if (line.startsWith("TICKET=")) {
                ticket = line.substring(7);
            }
        }
    } catch (UnsupportedEncodingException e) {
        log.error(e.getMessage(), e);
        throw new OKMException(
                ErrorCode.get(ErrorCode.ORIGIN_OKMZohoService, ErrorCode.CAUSE_UnsupportedEncoding),
                e.getMessage());
    } catch (MalformedURLException e) {
        log.error(e.getMessage(), e);
        throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMZohoService, ErrorCode.CAUSE_MalformedURL),
                e.getMessage());
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMZohoService, ErrorCode.CAUSE_IO),
                e.getMessage());
    }

    log.debug("getTicket: {}", ticket);
    return ticket;
}