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:edu.csh.coursebrowser.SchoolActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_course_browser);
    ListView lv = (ListView) this.findViewById(R.id.schools);
    this.setTitle("Course Browser");

    map_items = new HashMap<String, School>();
    map = new ArrayList<String>();
    this.sp = getPreferences(MODE_WORLD_READABLE);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, map);
    this.setTitle("Course Browser");

    if (!sp.contains("firstRun")) {
        SharedPreferences.Editor e = sp.edit();
        e.putBoolean("firstRun", false);
        e.commit();//w  w  w .j  a v a  2 s  . c om
        Intent intent = new Intent(SchoolActivity.this, AboutActivity.class);
        startActivity(intent);
    }

    addItem(new School("01", "Saunder's College of Business"));
    addItem(new School("03", "College of Engineering"));
    addItem(new School("05", "College of Liberal Arts"));
    addItem(new School("06", "Applied Science & Technology"));
    addItem(new School("08", "NTID"));
    addItem(new School("10", "College of Science"));
    addItem(new School("11", "Wellness"));
    addItem(new School("17", "Academic Services"));
    addItem(new School("20", "Imaging Arts and Sciences"));
    addItem(new School("30", "Interdisciplinary Studies"));
    addItem(new School("40", "GCCIS"));
    addItem(new School("50", "Institute for Sustainability"));

    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 School school = map_items.get(s);
            new AsyncTask<String, String, String>() {
                ProgressDialog p;

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

                protected String doInBackground(String... school) {
                    String params = "action=getDepartments&school=" + school[0] + "&quarter=20123";
                    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();
                        return null;
                    }
                    return back;
                }

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

                    try {
                        JSONObject jso = new JSONObject(s);
                        JSONArray jsa = new JSONArray(jso.getString("departments"));
                        ArrayList<Department> depts = new ArrayList<Department>();
                        for (int i = 0; i < jsa.length(); ++i) {
                            JSONObject obj = new JSONObject(jsa.get(i).toString());
                            depts.add(new Department(obj.getString("title"), obj.getString("id"),
                                    obj.getString("code")));
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                        new AlertError(SchoolActivity.this, "Invalid JSON From Server").show();
                        p.dismiss();
                        return;
                    }

                    Intent intent = new Intent(SchoolActivity.this, DepartmentActivity.class);
                    intent.putExtra("from", school.deptName);
                    intent.putExtra("args", s);
                    intent.putExtra("qCode", sp.getString("quarter", "20122"));
                    startActivity(intent);
                    p.dismiss();
                }
            }.execute(school.deptNum);
        }

    });

}

From source file:org.apache.cayenne.rop.http.HttpROPConnector.java

protected InputStream doRequest(Map<String, String> params) throws IOException {
    URLConnection connection = new URL(url).openConnection();

    if (readTimeout != null) {
        connection.setReadTimeout(readTimeout.intValue());
    }/*from w  w  w  . j a v a  2 s. c o  m*/

    addAuthHeader(connection);

    connection.setDoOutput(true);

    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    connection.setRequestProperty("charset", "utf-8");

    try (OutputStream output = connection.getOutputStream()) {
        output.write(ROPUtil.getParamsAsString(params).getBytes(StandardCharsets.UTF_8));
        output.flush();
    }

    return connection.getInputStream();
}

From source file:com.sabre.hack.travelachievementgame.DSCommHandler.java

@SuppressWarnings("deprecation")
public String sendRequest(String payLoad, String authToken) {
    URLConnection conn = null;
    String strRet = null;/*from   ww w.j  ava 2  s  .c  om*/
    try {
        URL urlConn = new URL(payLoad);

        conn = null;
        conn = urlConn.openConnection();

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

        conn.setRequestProperty("Authorization", "Bearer " + authToken);
        conn.setRequestProperty("Accept", "application/json");

        DataInputStream dataIn = new DataInputStream(conn.getInputStream());
        String strChunk = "";
        StringBuilder sb = new StringBuilder("");
        while (null != ((strChunk = dataIn.readLine())))
            sb.append(strChunk);

        strRet = sb.toString();
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        System.out.println("MalformedURLException in DSCommHandler");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        System.out.println("IOException in DSCommHandler: " + conn.getHeaderField(0));
        //         e.printStackTrace();
    }
    return strRet;
}

From source file:com.wavemaker.runtime.ws.SyndFeedService.java

/**
 * Reads from the InputStream of the specified URL and builds the feed object from the returned XML.
 * /*from  ww  w .j  a v  a 2  s  .  com*/
 * @param feedURL The URL to read feed from.
 * @param httpBasicAuthUsername The username for HTTP Basic Authentication.
 * @param httpBasicAuthPassword The password for HTTP Basic Authentication.
 * @param connectionTimeout HTTP connection timeout.
 * @return A feed object.
 */
@ExposeToClient
public Feed getFeedWithHttpConfig(String feedURL, String httpBasicAuthUsername, String httpBasicAuthPassword,
        int connectionTimeout) {
    URL url = null;
    try {
        url = new URL(feedURL);
    } catch (MalformedURLException e) {
        throw new WebServiceInvocationException(e);
    }

    SyndFeedInput input = new SyndFeedInput();
    try {
        URLConnection urlConn = url.openConnection();
        if (urlConn instanceof HttpURLConnection) {
            urlConn.setAllowUserInteraction(false);
            urlConn.setDoInput(true);
            urlConn.setDoOutput(false);
            ((HttpURLConnection) urlConn).setInstanceFollowRedirects(true);
            urlConn.setUseCaches(false);
            urlConn.setRequestProperty(USER_AGENT_KEY, USER_AGENT_VALUE);

            urlConn.setConnectTimeout(connectionTimeout);

            if (httpBasicAuthUsername != null && httpBasicAuthUsername.length() > 0) {
                String auth = httpBasicAuthPassword == null ? httpBasicAuthUsername
                        : httpBasicAuthUsername + ":" + httpBasicAuthPassword;
                urlConn.setRequestProperty(BASIC_AUTH_KEY,
                        BASIC_AUTH_VALUE_PREFIX + Base64.encodeBase64URLSafeString(auth.getBytes()));
            }
        }
        SyndFeed feed = input.build(new XmlReader(urlConn));
        return FeedBuilder.getFeed(feed);
    } catch (IllegalArgumentException e) {
        throw new WebServiceInvocationException(e);
    } catch (FeedException e) {
        throw new WebServiceInvocationException(e);
    } catch (IOException e) {
        throw new WebServiceInvocationException(e);
    }
}

From source file:org.apache.ode.jbi.JbiTestBase.java

protected void go() throws Exception {
    boolean manualDeploy = Boolean.parseBoolean("" + testProperties.getProperty("manualDeploy"));
    if (!manualDeploy)
        enableProcess(getTestName(), true);

    try {/*ww  w .  j a  va 2  s. c  om*/
        int i = 0;
        boolean loop;
        do {
            String prefix = i == 0 ? "" : "" + i;
            loop = i == 0;

            {
                String deploy = testProperties.getProperty(prefix + "deploy");
                if (deploy != null) {
                    loop = true;
                    enableProcess(getTestName() + "/" + deploy, true);
                }
            }
            {
                String undeploy = testProperties.getProperty(prefix + "undeploy");
                if (undeploy != null) {
                    loop = true;
                    enableProcess(getTestName() + "/" + undeploy, false);
                }
            }

            String request = testProperties.getProperty(prefix + "request");
            if (request != null && request.startsWith("@")) {
                request = inputStreamToString(
                        getClass().getResourceAsStream("/" + getTestName() + "/" + request.substring(1)));
            }
            String expectedResponse = testProperties.getProperty(prefix + "response");
            {
                String delay = testProperties.getProperty(prefix + "delay");
                if (delay != null) {
                    loop = true;
                    long d = Long.parseLong(delay);
                    log.debug("Sleeping " + d + " ms");
                    Thread.sleep(d);
                }
            }
            {
                String httpUrl = testProperties.getProperty(prefix + "http.url");
                if (httpUrl != null && request != null) {
                    loop = true;
                    log.debug(getTestName() + " sending http request to " + httpUrl + " request: " + request);
                    URLConnection connection = new URL(httpUrl).openConnection();
                    connection.setDoOutput(true);
                    connection.setDoInput(true);
                    //Send request
                    OutputStream os = connection.getOutputStream();
                    PrintWriter wt = new PrintWriter(os);
                    wt.print(request);
                    wt.flush();
                    wt.close();
                    // Read the response.
                    String result = inputStreamToString(connection.getInputStream());

                    log.debug(getTestName() + " have result: " + result);
                    matchResponse(expectedResponse, result, true);
                }
            }
            {
                if (testProperties.getProperty(prefix + "nmr.service") != null && request != null) {
                    loop = true;
                    InOut io = smxClient.createInOutExchange();
                    io.setService(QName.valueOf(testProperties.getProperty(prefix + "nmr.service")));
                    io.setOperation(QName.valueOf(testProperties.getProperty(prefix + "nmr.operation")));
                    io.getInMessage()
                            .setContent(new StreamSource(new ByteArrayInputStream(request.getBytes())));
                    smxClient.sendSync(io, 20000);
                    if (io.getStatus() == ExchangeStatus.ACTIVE) {
                        assertNotNull(io.getOutMessage());
                        String result = new SourceTransformer().contentToString(io.getOutMessage());
                        matchResponse(expectedResponse, result, true);
                        smxClient.done(io);
                    } else {
                        matchResponse(expectedResponse, "", false);
                    }
                }
            }

            i++;
        } while (loop);

    } finally {
        if (!manualDeploy)
            enableProcess(getTestName(), false);
    }
}

From source file:com.seleritycorp.common.base.coreservices.RawCoreServiceClient.java

private String getRawResponse(String rawRequest, int timeoutMillis) throws IOException {
    URLConnection connection = apiUrl.openConnection();
    connection.setRequestProperty("Accept", "text/plain");
    connection.setRequestProperty("Content-type", "application/json");
    connection.setRequestProperty("User-Agent", client);
    connection.setDoOutput(true);
    connection.setReadTimeout(timeoutMillis);

    final OutputStream out = connection.getOutputStream();
    out.write(rawRequest.getBytes(StandardCharsets.UTF_8));
    out.flush();/*from  w  w  w . j av a 2 s.  c  o  m*/
    out.close();

    log.debug("wrote request " + rawRequest + " (timeout wanted: " + timeoutMillis + ", actual: "
            + connection.getReadTimeout() + ")");

    String response = null;
    try (final InputStream in = connection.getInputStream()) {
        response = IOUtils.toString(in, StandardCharsets.UTF_8);
    }

    return response;
}

From source file:org.apache.jcs.auxiliary.lateral.http.broadcast.LateralCacheThread.java

/** Description of the Method */
public void writeObj(URLConnection connection, ICacheElement cb) {
    try {/*from w  ww .  jav  a 2 s  .c o  m*/
        connection.setUseCaches(false);
        connection.setRequestProperty("CONTENT_TYPE", "application/octet-stream");
        connection.setDoOutput(true);
        connection.setDoInput(true);
        ObjectOutputStream os = new ObjectOutputStream(connection.getOutputStream());
        log.debug("os = " + os);

        // Write the ICacheItem to the ObjectOutputStream
        log.debug("Writing  ICacheItem.");

        os.writeObject(cb);
        os.flush();

        log.debug("closing output stream");

        os.close();
    } catch (IOException e) {
        log.error(e);
    }
    // end catch
}

From source file:org.exoplatform.wcm.connector.fckeditor.GadgetConnector.java

/**
 * Creates the file element.//www  .j a v a  2s.co m
 *
 * @param document The document.
 * @param applicationCategory The application category.
 *
 * @return the element
 *
 * @throws Exception the exception
 */
private Element createFileElement(Document document, ApplicationCategory applicationCategory, String host)
        throws Exception {
    Element files = document.createElement("Files");
    List<Application> listApplication = applicationRegistryService.getApplications(applicationCategory,
            ApplicationType.GADGET);
    for (Application application : listApplication) {
        Gadget gadget = gadgetRegistryService.getGadget(application.getApplicationName());
        Element file = document.createElement("File");
        file.setAttribute("name", gadget.getName());
        file.setAttribute("fileType", "nt_unstructured");
        file.setAttribute("size", "0");
        file.setAttribute("thumbnail", gadget.getThumbnail());
        file.setAttribute("description", gadget.getDescription());

        String fullurl = "";
        if (gadget.isLocal()) {
            fullurl = "/" + PortalContainer.getCurrentRestContextName() + "/" + gadget.getUrl();
        } else {
            fullurl = gadget.getUrl();
        }
        file.setAttribute("url", fullurl);

        String data = "{\"context\":{\"country\":\"US\",\"language\":\"en\"},\"gadgets\":[{\"moduleId\":0,\"url\":\""
                + fullurl + "\",\"prefs\":[]}]}";
        URL url = new URL(host + "/eXoGadgetServer/gadgets/metadata");
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data);
        wr.flush();
        String strMetadata = IOUtils.toString(conn.getInputStream(), "UTF-8");
        wr.close();
        JSONObject metadata = new JSONObject(strMetadata.toString());

        ConversationState conversationState = ConversationState.getCurrent();
        String userId = conversationState.getIdentity().getUserId();
        String token = createToken(gadget.getUrl(), userId, userId, new Random().nextLong(), "default");
        JSONObject obj = metadata.getJSONArray("gadgets").getJSONObject(0);
        obj.put("secureToken", token);

        file.setAttribute("metadata", metadata.toString());
        files.appendChild(file);
    }
    return files;
}

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

@SuppressWarnings("unchecked")
public T fetchArray() {
    ArrayList<E> array = new ArrayList<E>();

    try {/*w  ww.j  av  a  2s  . com*/
        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");
        conn.addRequestProperty("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();

        final ArrayList<E> objectList = new ArrayList<E>();

        JSONObject jsonObject;
        jsonObject = new JSONObject(jsonString);

        JSONArray jsonRootArray;
        jsonRootArray = jsonObject.getJSONObject("d").getJSONArray(liste);
        android.util.Log.d("JSON", jsonRootArray.toString());
        for (int i = 0; i < jsonRootArray.length(); i++) {
            objectList.add(gson.fromJson(jsonRootArray.getJSONObject(i).toString(), typeOfClass));
        }

        array = objectList;
    } catch (final IOException e) {
        e.printStackTrace();
    } catch (final JSONException e) {
        e.printStackTrace();
    }

    return (T) array;
}

From source file:org.deegree.enterprise.servlet.SimpleProxyServlet.java

/**
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 *//* ww w . j  av a 2 s  .c  o  m*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    InputStream is = null;
    OutputStream os = null;
    try {
        String query = request.getQueryString();
        Map<String, String> map = KVP2Map.toMap(query);
        if (removeCredentials) {
            map.remove("USER");
            map.remove("PASSWORD");
            map.remove("SESSIONID");
            query = "";
            for (String key : map.keySet()) {
                query += key + "=" + map.get(key) + "&";
            }
            query = query.substring(0, query.length() - 1);
        }
        String service = getService(map);
        String hostAddr = host.get(service);
        String req = hostAddr + "?" + query;
        URL url = new URL(req);
        LOG.logDebug("forward URL: " + url);

        URLConnection con = url.openConnection();
        con.setDoInput(true);
        con.setDoOutput(false);
        is = con.getInputStream();
        response.setContentType(con.getContentType());
        response.setCharacterEncoding(con.getContentEncoding());
        os = response.getOutputStream();
        int read = 0;
        byte[] buf = new byte[16384];
        if (LOG.getLevel() == ILogger.LOG_DEBUG) {
            while ((read = is.read(buf)) > -1) {
                os.write(buf, 0, read);
                LOG.logDebug(new String(buf, 0, read,
                        con.getContentEncoding() == null ? "UTF-8" : con.getContentEncoding()));
            }
        } else {
            while ((read = is.read(buf)) > -1) {
                os.write(buf, 0, read);
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
        response.setContentType("text/plain; charset=" + CharsetUtils.getSystemCharset());
        os.write(StringTools.stackTraceToString(e).getBytes());
    } finally {
        try {
            is.close();
        } catch (Exception e) {
            // try to do what ?
        }
        try {
            os.close();
        } catch (Exception e) {
            // try to do what ?
        }
    }
}