Example usage for java.net URLConnection setDoInput

List of usage examples for java.net URLConnection setDoInput

Introduction

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

Prototype

public void setDoInput(boolean doinput) 

Source Link

Document

Sets the value of the doInput field for this URLConnection to the specified value.

Usage

From source file:com.otisbean.keyring.Ring.java

/**
 * Export data to the specified file./*from ww  w  .ja  v  a 2 s  .c  om*/
 * 
 * @param outFile Path to the output file
 * @throws IOException
 * @throws GeneralSecurityException
 */
public void save(String outFile) throws IOException, GeneralSecurityException {
    log("save(" + outFile + ")");
    if (outFile.startsWith("http")) {
        URL url = new URL(outFile);
        URLConnection urlConn = url.openConnection();
        urlConn.setDoInput(true);
        urlConn.setDoOutput(true);
        urlConn.setUseCaches(false);
        urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream());
        String message = "data=" + URLEncoder.encode(getExportData().toJSONString(), "UTF-8");
        dos.writeBytes(message);
        dos.flush();
        dos.close();

        // the server responds by saying 
        // "OK" or "ERROR: blah blah"

        BufferedReader br = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
        String s = br.readLine();
        if (!s.equals("OK")) {
            StringBuilder sb = new StringBuilder();
            sb.append("Failed to save to URL '");
            sb.append(url);
            sb.append("': ");
            while ((s = br.readLine()) != null) {
                sb.append(s);
            }
            throw new IOException(sb.toString());
        }
        br.close();
    } else {
        Writer writer = getWriter(outFile);
        getExportData().writeJSONString(writer);
        closeWriter(writer, outFile);
    }
}

From source file:org.apache.xmlrpc.applet.SimpleXmlRpcClient.java

/**
 * Generate an XML-RPC request and send it to the server. Parse the result
 * and return the corresponding Java object.
 *
 * @exception XmlRpcException If the remote host returned a fault message.
 * @exception IOException If the call could not be made for lower level
 *          problems.//from  w  w w .ja v  a  2  s  .  c  o m
 */
public Object execute(String method, Vector arguments) throws XmlRpcException, IOException {
    fault = false;
    long now = System.currentTimeMillis();
    try {
        StringBuffer strbuf = new StringBuffer();
        XmlWriter writer = new XmlWriter(strbuf);
        writeRequest(writer, method, arguments);
        byte[] request = strbuf.toString().getBytes();
        URLConnection con = url.openConnection();
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setUseCaches(false);
        con.setAllowUserInteraction(false);
        con.setRequestProperty("Content-Length", Integer.toString(request.length));
        con.setRequestProperty("Content-Type", "text/xml");
        // con.connect ();
        OutputStream out = con.getOutputStream();
        out.write(request);
        out.flush();
        InputStream in = con.getInputStream();
        parse(in);
        System.out.println("result = " + result);
    } catch (Exception x) {
        x.printStackTrace();
        throw new IOException(x.getMessage());
    }
    if (fault) {
        // generate an XmlRpcException
        XmlRpcException exception = null;
        try {
            Hashtable f = (Hashtable) result;
            String faultString = (String) f.get("faultString");
            int faultCode = Integer.parseInt(f.get("faultCode").toString());
            exception = new XmlRpcException(faultCode, faultString.trim());
        } catch (Exception x) {
            throw new XmlRpcException(0, "Invalid fault response");
        }
        throw exception;
    }
    System.out.println("Spent " + (System.currentTimeMillis() - now) + " in request");
    return result;
}

From source file:org.ohie.pocdemo.form.util.InfoMan.java

private String invoke(final String req) throws Exception {
    log.info("Sending to " + URL + "\n" + req);
    final URLConnection ucon = new URL(URL).openConnection();
    ucon.setRequestProperty("Accept", "text/xml");
    ucon.setRequestProperty("Accept-Charset", "utf-8");
    ucon.setRequestProperty("Content-Type", "text/xml; charset=utf-8");

    String userPassword = USERNAME + ":" + PASSWORD;
    String encoding = new sun.misc.BASE64Encoder().encode(userPassword.getBytes());

    ucon.setRequestProperty("Authorization", "Basic " + encoding);
    ucon.setDoInput(true);
    ucon.setDoOutput(true);//from   w w  w .  j a  v a  2 s. co m
    ucon.getOutputStream().write(req.getBytes());
    final InputStream in = Util.getRawStream(ucon);
    final String rsp;
    try {
        rsp = Util.readStream(in);
    } finally {
        in.close();
    }
    log.info("Received from " + URL + "\n" + rsp);
    return rsp;
}

From source file:org.codehaus.groovy.grails.web.pages.GroovyPageMetaInfo.java

/**
 * Attempts to establish what the last modified date of the given resource is. If the last modified date cannot
 * be etablished -1 is returned//from   w ww  . j  av a  2s.  c o m
 *
 * @param resource The Resource to evaluate
 * @return The last modified date or -1
 */
private long establishLastModified(Resource resource) {
    if (resource == null)
        return -1;

    if (resource instanceof FileSystemResource) {
        return ((FileSystemResource) resource).getFile().lastModified();
    }

    long last;
    URLConnection urlc = null;

    try {
        URL url = resource.getURL();
        if ("file".equals(url.getProtocol())) {
            File file = new File(url.getFile());
            if (file.exists()) {
                return file.lastModified();
            }
        }
        urlc = url.openConnection();
        urlc.setDoInput(false);
        urlc.setDoOutput(false);
        last = urlc.getLastModified();
    } catch (FileNotFoundException fnfe) {
        last = -1;
    } catch (IOException e) {
        last = -1;
    } finally {
        if (urlc != null) {
            try {
                InputStream is = urlc.getInputStream();
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                // ignore
            }
        }
    }

    return last;
}

From source file:edu.caltechUcla.sselCassel.projects.jMarkets.frontdesk.web.data.SessionBean.java

/**
 * Connect to the JMarkets server and start the session defined by the given SessionDef object.
 *  Return the session Id of the created session
 *//*from w ww .j av  a2s . c o  m*/
private int executeSession(String path, String name, SessionDef session) {
    try {
        URL servlet = new URL(path + "/servlet/ServletReceiver");
        Request req = new Request(Request.SERVER_INIT_REQUEST);

        req.addIntInfo("numClients", numSubjects);
        req.addIntInfo("updateProtocol", JMConstants.HTTP_UPDATE_PROTOCOL);
        req.addIntInfo("updateTime", 100);
        req.addStringInfo("name", name);
        req.addInfo("session", session);

        URLConnection servletConnection = servlet.openConnection();

        servletConnection.setDoInput(true);
        servletConnection.setDoOutput(true);
        servletConnection.setUseCaches(false);
        servletConnection.setDefaultUseCaches(false);
        servletConnection.setRequestProperty("Content-Type", "application/octet-stream");

        ObjectOutputStream outputToServlet = new ObjectOutputStream(servletConnection.getOutputStream());

        outputToServlet.writeObject(req);
        outputToServlet.flush();
        outputToServlet.close();

        ObjectInputStream inputFromServlet = new ObjectInputStream(servletConnection.getInputStream());
        Response res = (Response) inputFromServlet.readObject();
        int sessionId = res.getIntInfo("sessionId");

        inputFromServlet.close();

        return sessionId;

    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    return -1;
}

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

private URLConnection getUrlConnection(HttpServletRequest request, String method, String requestBody,
        String forwardUrl) throws MalformedURLException, IOException, ProtocolException {
    final URL url = new URL(forwardUrl);
    final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));

    URLConnection urlConnection = url.openConnection(proxy);

    Map<String, String> requestHeaders = getRequestHeaders(request);
    requestHeaders.put("Host", urlConnection.getURL().getHost());

    ((HttpURLConnection) urlConnection).setRequestMethod(method);

    if (forwardUrl.startsWith("https")) {
        SSLSocketFactory sslSocketFactory = null;
        try {// w w w.  ja va 2 s .  com
            sslSocketFactory = getSSLSocketFactory();
        } catch (KeyManagementException e) {
            throw new IOException("Exception caught while setting up SSL props : ", e);
        } catch (NoSuchAlgorithmException e) {
            throw new IOException("Exception caught while setting up SSL props : ", e);
        }
        ((HttpsURLConnection) urlConnection).setSSLSocketFactory(sslSocketFactory);
    }

    urlConnection.setDoInput(true);

    setHeaders(urlConnection, requestHeaders);

    setDoOutput(method, requestBody, urlConnection);

    return urlConnection;
}

From source file:com.hpe.application.automation.tools.srf.run.RunFromSrfBuilder.java

private String loginToSrf() throws MalformedURLException, IOException, ConnectException {
    String authorizationsAddress = _ftaasServerAddress.concat("/rest/security/authorizations/access-tokens");
    //    .concat("/?TENANTID="+_tenant);
    Writer writer = null;/*www  . ja va2s  . c  om*/
    // login //
    JSONObject login = new JSONObject();
    login.put("loginName", _app);
    login.put("password", _secret);
    OutputStream out;
    URL loginUrl = new URL(authorizationsAddress);
    URLConnection loginCon;

    if (_ftaasServerAddress.startsWith("http://")) {
        loginCon = (HttpURLConnection) loginUrl.openConnection();
        loginCon.setDoOutput(true);
        loginCon.setDoInput(true);
        ((HttpURLConnection) loginCon).setRequestMethod("POST");
        loginCon.setRequestProperty("Content-Type", "application/json");
        out = loginCon.getOutputStream();
    } else {
        loginCon = loginUrl.openConnection();
        loginCon.setDoOutput(true);
        loginCon.setDoInput(true);
        ((HttpsURLConnection) loginCon).setRequestMethod("POST");
        loginCon.setRequestProperty("Content-Type", "application/json");
        ((HttpsURLConnection) loginCon).setSSLSocketFactory(_factory);
        out = loginCon.getOutputStream();
    }

    writer = new OutputStreamWriter(out);
    writer.write(login.toString());
    writer.flush();
    out.flush();
    out.close();
    int responseCode = ((HttpURLConnection) loginCon).getResponseCode();
    systemLogger.fine(String.format("SRF login received response code: %d", responseCode));
    BufferedReader br = new BufferedReader(new InputStreamReader((loginCon.getInputStream())));
    StringBuffer response = new StringBuffer();
    String line;
    while ((line = br.readLine()) != null) {
        response.append(line);
    }
    String tmp = response.toString();
    int n = tmp.length();

    return tmp.substring(1, n - 1);
}

From source file:junk.gui.HazardDataSetCalcCondorApp.java

/**
 * this connects to the servlet on web server to check if dataset name already exists
 * or computation have already been for these parameter settings.
 * @return/*from   w  w  w .ja  va2s.c o m*/
 */
private Object checkForHazardMapComputation() {

    try {
        if (D)
            System.out.println("starting to make connection with servlet");
        URL hazardMapServlet = new URL(DATASET_CHECK_SERVLET_URL);

        URLConnection servletConnection = hazardMapServlet.openConnection();
        if (D)
            System.out.println("connection established");

        // inform the connection that we will send output and accept input
        servletConnection.setDoInput(true);
        servletConnection.setDoOutput(true);

        // Don't use a cached version of URL connection.
        servletConnection.setUseCaches(false);
        servletConnection.setDefaultUseCaches(false);
        // Specify the content type that we will send binary data
        servletConnection.setRequestProperty("Content-Type", "application/octet-stream");

        ObjectOutputStream toServlet = new ObjectOutputStream(servletConnection.getOutputStream());

        //sending the parameters info. to the servlet
        toServlet.writeObject(getParametersInfo());

        //sending the dataset id to the servlet
        toServlet.writeObject(datasetIdText.getText());

        toServlet.flush();
        toServlet.close();

        // Receive the datasetnumber from the servlet after it has received all the data
        ObjectInputStream fromServlet = new ObjectInputStream(servletConnection.getInputStream());
        Object obj = fromServlet.readObject();
        //if(D) System.out.println("Receiving the Input from the Servlet:"+success);
        fromServlet.close();
        return obj;

    } catch (Exception e) {
        ExceptionWindow bugWindow = new ExceptionWindow(this, e, getParametersInfo());
        bugWindow.setVisible(true);
        bugWindow.pack();

    }
    return null;
}

From source file:junk.gui.HazardDataSetCalcCondorApp.java

/**
 * sets up the connection with the servlet on the server (gravity.usc.edu)
 *///www .  jav a  2 s.  c o m
private void sendParametersToServlet(SitesInGriddedRegion regionSites,
        ScalarIntensityMeasureRelationshipAPI imr, String eqkRupForecastLocation) {

    try {
        if (D)
            System.out.println("starting to make connection with servlet");
        URL hazardMapServlet = new URL(SERVLET_URL);

        URLConnection servletConnection = hazardMapServlet.openConnection();
        if (D)
            System.out.println("connection established");

        // inform the connection that we will send output and accept input
        servletConnection.setDoInput(true);
        servletConnection.setDoOutput(true);

        // Don't use a cached version of URL connection.
        servletConnection.setUseCaches(false);
        servletConnection.setDefaultUseCaches(false);
        // Specify the content type that we will send binary data
        servletConnection.setRequestProperty("Content-Type", "application/octet-stream");

        ObjectOutputStream toServlet = new ObjectOutputStream(servletConnection.getOutputStream());

        //sending the object of the gridded region sites to the servlet
        toServlet.writeObject(regionSites);
        //sending the IMR object to the servlet
        toServlet.writeObject(imr);
        //sending the EQK forecast object to the servlet
        toServlet.writeObject(eqkRupForecastLocation);
        //send the X values in a arraylist
        ArrayList list = new ArrayList();
        for (int i = 0; i < function.getNum(); ++i)
            list.add(new String("" + function.getX(i)));
        toServlet.writeObject(list);
        // send the MAX DISTANCE
        toServlet.writeObject(maxDistance);

        //sending email address to the servlet
        toServlet.writeObject(emailText.getText());
        //sending the parameters info. to the servlet
        toServlet.writeObject(getParametersInfo());

        //sending the dataset id to the servlet
        toServlet.writeObject(datasetIdText.getText());

        toServlet.flush();
        toServlet.close();

        // Receive the datasetnumber from the servlet after it has received all the data
        ObjectInputStream fromServlet = new ObjectInputStream(servletConnection.getInputStream());
        String dataset = fromServlet.readObject().toString();
        JOptionPane.showMessageDialog(this, dataset);
        if (D)
            System.out.println("Receiving the Input from the Servlet:" + dataset);
        fromServlet.close();

    } catch (Exception e) {
        ExceptionWindow bugWindow = new ExceptionWindow(this, e, getParametersInfo());
        bugWindow.setVisible(true);
        bugWindow.pack();
    }
}

From source file:net.solarnetwork.node.support.HttpClientSupport.java

/**
 * Get a URLConnection for a specific URL and HTTP method.
 * //from w  ww. j a v  a 2s.  com
 * <p>
 * If the httpMethod equals {@code POST} then the connection's
 * {@code doOutput} property will be set to <em>true</em>, otherwise it will
 * be set to <em>false</em>. The {@code doInput} property is always set to
 * <em>true</em>.
 * </p>
 * 
 * <p>
 * This method also sets up the request property
 * {@code Accept-Encoding: gzip,deflate} so the response can be compressed.
 * The {@link #getInputSourceFromURLConnection(URLConnection)} automatically
 * handles compressed responses.
 * </p>
 * 
 * <p>
 * If the {@link #getSslService()} property is configured and the URL
 * represents an HTTPS connection, then that factory will be used to for the
 * connection.
 * </p>
 * 
 * @param url
 *        the URL to connect to
 * @param httpMethod
 *        the HTTP method
 * @param accept
 *        the HTTP Accept header value
 * @return the URLConnection
 * @throws IOException
 *         if any IO error occurs
 */
protected URLConnection getURLConnection(String url, String httpMethod, String accept) throws IOException {
    URL connUrl = new URL(url);
    URLConnection conn = connUrl.openConnection();
    if (conn instanceof HttpURLConnection) {
        HttpURLConnection hConn = (HttpURLConnection) conn;
        hConn.setRequestMethod(httpMethod);
    }
    if (sslService != null && conn instanceof HttpsURLConnection) {
        SSLService service = sslService.service();
        if (service != null) {
            SSLSocketFactory factory = service.getSolarInSocketFactory();
            if (factory != null) {
                HttpsURLConnection hConn = (HttpsURLConnection) conn;
                hConn.setSSLSocketFactory(factory);
            }
        }
    }
    conn.setRequestProperty("Accept", accept);
    conn.setRequestProperty("Accept-Encoding", "gzip,deflate");
    conn.setDoInput(true);
    conn.setDoOutput(HTTP_METHOD_POST.equalsIgnoreCase(httpMethod));
    conn.setConnectTimeout(this.connectionTimeout);
    conn.setReadTimeout(connectionTimeout);
    return conn;
}