Example usage for java.io OutputStreamWriter write

List of usage examples for java.io OutputStreamWriter write

Introduction

In this page you can find the example usage for java.io OutputStreamWriter write.

Prototype

public void write(int c) throws IOException 

Source Link

Document

Writes a single character.

Usage

From source file:com.example.android.networkconnect.MainActivity.java

private String httpstestconnect(String urlString) throws IOException {
    CookieManager msCookieManager = new CookieManager();

    URL url = new URL(urlString);

    if (url.getProtocol().toLowerCase().equals("https")) {
        trustAllHosts();//www.  ja va 2 s  . com

        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

        try {

            String headerName = null;

            for (int i = 1; (headerName = conn.getHeaderFieldKey(i)) != null; i++) {
                //data=data+"Header Nme : " + headerName;
                //data=data+conn.getHeaderField(i);
                // Log.i (TAG,headerName);
                Log.i(TAG, headerName + ": " + conn.getHeaderField(i));
            }

            //  Map<String, List<String>> headerFields = conn.getHeaderFields();
            //List<String> cookiesHeader = headerFields.get("Set-Cookie");

            //if(cookiesHeader != null)
            //{
            //  for (String cookie : cookiesHeader)
            // {
            //   msCookieManager.getCookieStore().add(null,HttpCookie.parse(cookie).get(0));

            //}
            //}

        } catch (Exception e) {
            Log.i(TAG, "Erreur Cookie" + e);
        }

        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);

        conn.setChunkedStreamingMode(0);

        conn.setRequestProperty("User-Agent", "e-venement-app/");

        //if(msCookieManager.getCookieStore().getCookies().size() > 0)
        //{
        //        conn.setRequestProperty("Cookie",
        //            TextUtils.join(",", msCookieManager.getCookieStore().getCookies()));
        //}

        // conn= (HttpsURLConnection) url.wait(); ;
        //(HttpsURLConnection) url.openConnection();

        final String password = "android2015@";

        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
        writer.getEncoding();
        writer.write("&signin[username]=antoine");
        writer.write("&signin[password]=android2015@");
        //writer.write("&signin[_csrf_token]="+CSRFTOKEN);
        writer.flush();
        //Log.i(TAG,"Writer: "+writer.toString());

        //   conn.connect();

        String data = null;

        //
        if (conn.getInputStream() != null) {
            Log.i(TAG, readIt(conn.getInputStream(), 2500));
            data = readIt(conn.getInputStream(), 7500);
        }

        //  return conn.getResponseCode();
        return data;
        //return readIt(inputStream,1028);
    }

    else {
        return url.getProtocol();
    }

}

From source file:au.org.ala.layers.dao.LayerIntersectDAOImpl.java

ArrayList<String> remoteSampling(IntersectionFile[] intersectionFiles, double[][] points,
        IntersectCallback callback) {/*  w w w.j a  v  a2  s .co m*/
    logger.info("begin REMOTE sampling, number of threads " + intersectConfig.getThreadCount()
            + ", number of layers=" + intersectionFiles.length + ", number of coordinates=" + points.length);

    ArrayList<String> output = null;

    try {
        long start = System.currentTimeMillis();
        URL url = new URL(intersectConfig.getLayerIndexUrl() + "/intersect/batch");
        URLConnection c = url.openConnection();
        c.setDoOutput(true);

        OutputStreamWriter out = null;
        try {
            out = new OutputStreamWriter(c.getOutputStream());
            out.write("fids=");
            for (int i = 0; i < intersectionFiles.length; i++) {
                if (i > 0) {
                    out.write(",");
                }
                out.write(intersectionFiles[i].getFieldId());
            }
            out.write("&points=");
            for (int i = 0; i < points.length; i++) {
                if (i > 0) {
                    out.write(",");
                }
                out.write(String.valueOf(points[i][1]));
                out.write(",");
                out.write(String.valueOf(points[i][0]));
            }
            out.flush();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }

        JSONObject jo = JSONObject.fromObject(IOUtils.toString(c.getInputStream()));

        String checkUrl = jo.getString("statusUrl");

        //check status
        boolean notFinished = true;
        String downloadUrl = null;
        while (notFinished) {
            //wait 5s before querying status
            Thread.sleep(5000);

            jo = JSONObject.fromObject(IOUtils.toString(new URI(checkUrl).toURL().openStream()));

            if (jo.containsKey("error")) {
                notFinished = false;
            } else if (jo.containsKey("status")) {
                String status = jo.getString("status");

                if ("finished".equals(status)) {
                    downloadUrl = jo.getString("downloadUrl");
                    notFinished = false;
                } else if ("cancelled".equals(status) || "error".equals(status)) {
                    notFinished = false;
                }
            }
        }

        ZipInputStream zis = null;
        CSVReader csv = null;
        InputStream is = null;
        ArrayList<StringBuilder> tmpOutput = new ArrayList<StringBuilder>();
        long mid = System.currentTimeMillis();
        try {
            is = new URI(downloadUrl).toURL().openStream();
            zis = new ZipInputStream(is);
            ZipEntry ze = zis.getNextEntry();
            csv = new CSVReader(new InputStreamReader(zis));

            for (int i = 0; i < intersectionFiles.length; i++) {
                tmpOutput.add(new StringBuilder());
            }
            String[] line;
            int row = 0;
            csv.readNext(); //discard header
            while ((line = csv.readNext()) != null) {
                //order is consistent with request
                for (int i = 2; i < line.length && i - 2 < tmpOutput.size(); i++) {
                    if (row > 0) {
                        tmpOutput.get(i - 2).append("\n");
                    }
                    tmpOutput.get(i - 2).append(line[i]);
                }
                row++;
            }

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            if (zis != null) {
                try {
                    zis.close();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
            if (csv != null) {
                try {
                    csv.close();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }

        output = new ArrayList<String>();
        for (int i = 0; i < tmpOutput.size(); i++) {
            output.add(tmpOutput.get(i).toString());
            tmpOutput.set(i, null);
        }

        long end = System.currentTimeMillis();

        logger.info("sample time for " + 5 + " layers and " + 3 + " coordinates: get response=" + (mid - start)
                + "ms, write response=" + (end - mid) + "ms");

    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
    return output;
}

From source file:com.netscape.cms.servlet.connector.ConnectorServlet.java

public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    boolean running_state = CMS.isInRunningState();

    if (!running_state)
        throw new IOException("CMS server is not ready to serve.");

    HttpServletRequest req = request;//from  ww w.j a v  a2 s .c om
    HttpServletResponse resp = response;

    CMSRequest cmsRequest = newCMSRequest();

    // set argblock
    cmsRequest.setHttpParams(CMS.createArgBlock(toHashtable(request)));

    // set http request
    cmsRequest.setHttpReq(request);

    // set http response
    cmsRequest.setHttpResp(response);

    // set servlet config.
    cmsRequest.setServletConfig(mConfig);

    // set servlet context.
    cmsRequest.setServletContext(mConfig.getServletContext());

    char[] content = null;
    String encodedreq = null;
    String method = null;
    int len = -1;
    IPKIMessage msg = null;
    IPKIMessage replymsg = null;

    // NOTE must read all bufer before redoing handshake for
    // ssl client auth for client auth to work.

    // get request method
    method = req.getMethod();

    // get content length
    len = request.getContentLength();

    // get content, a base 64 encoded serialized request.
    if (len > 0) {
        InputStream in = request.getInputStream();
        InputStreamReader inreader = new InputStreamReader(in, "UTF8");
        BufferedReader reader = new BufferedReader(inreader, len);

        content = new char[len];
        int done = reader.read(content, 0, len);
        int total = done;

        while (done >= 0 && total < len) {
            done = reader.read(content, total, len - total);
            total += done;
        }
        reader.close();
        encodedreq = new String(content);
    }

    // force client auth handshake, validate RA and get RA's Id.
    // NOTE must do this after all contents are read for ssl
    // redohandshake to work

    X509Certificate peerCert;

    try {
        peerCert = getPeerCert(req);
    } catch (EBaseException e) {
        mAuthority.log(ILogger.LL_SECURITY, CMS.getLogMessage("CMSGW_HAS_NO_CLIENT_CERT"));
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    }

    if (peerCert == null) {
        // XXX log something here.
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    // authenticate RA

    String RA_Id = null;
    String raUserId = null;
    IAuthToken token = null;

    try {
        token = authenticate(request);
        raUserId = token.getInString("userid");
        RA_Id = peerCert.getSubjectDN().toString();
    } catch (EInvalidCredentials e) {
        // already logged.
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    } catch (EBaseException e) {
        // already logged.
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    mAuthority.log(ILogger.LL_INFO, "Remote Authority authenticated: " + peerCert.getSubjectDN());

    // authorize
    AuthzToken authzToken = null;

    try {
        authzToken = authorize(mAclMethod, token, mAuthzResourceName, "submit");
    } catch (Exception e) {
        // do nothing for now
    }

    if (authzToken == null) {
        cmsRequest.setStatus(ICMSRequest.UNAUTHORIZED);
        return;
    }

    // after cert validated, check http request.
    if (!method.equalsIgnoreCase("POST")) {
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        return;
    }
    if (len <= 0) {
        resp.sendError(HttpServletResponse.SC_LENGTH_REQUIRED);
        return;
    }

    // now process request.

    CMS.debug("ConnectorServlet: process request RA_Id=" + RA_Id);
    try {
        // decode request.
        msg = (IPKIMessage) mReqEncoder.decode(encodedreq);
        // process request
        replymsg = processRequest(RA_Id, raUserId, msg, token);
    } catch (IOException e) {
        CMS.debug("ConnectorServlet: service " + e.toString());
        CMS.debug(e);
        mAuthority.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_IO_ERROR_REMOTE_REQUEST", e.toString()));
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    } catch (EBaseException e) {
        CMS.debug("ConnectorServlet: service " + e.toString());
        CMS.debug(e);
        mAuthority.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_IO_ERROR_REMOTE_REQUEST", e.toString()));
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    } catch (Exception e) {
        CMS.debug("ConnectorServlet: service " + e.toString());
        CMS.debug(e);
    }

    CMS.debug("ConnectorServlet: done processRequest");

    // encode reply
    try {
        String encodedrep = mReqEncoder.encode(replymsg);

        resp.setStatus(HttpServletResponse.SC_OK);
        resp.setContentType("text/html");
        resp.setContentLength(encodedrep.length());

        // send reply
        OutputStream out = response.getOutputStream();
        OutputStreamWriter writer = new OutputStreamWriter(out, "UTF8");

        writer.write(encodedrep);
        writer.flush();
        writer.close();
        out.flush();
    } catch (Exception e) {
        CMS.debug("ConnectorServlet: error writing e=" + e.toString());
    }
    CMS.debug("ConnectorServlet: send response RA_Id=" + RA_Id);
}

From source file:com.truebanana.http.HTTPRequest.java

/**
 * Executes this {@link HTTPRequest} asynchronously. To hook to events or listen to the server response, you must provide an {@link HTTPResponseListener} using {@link HTTPRequest#setHTTPResponseListener(HTTPResponseListener)}.
 *
 * @return This {@link HTTPRequest}/*from w  w  w . j  a  v a 2 s.com*/
 */
public HTTPRequest executeAsync() {
    Async.executeAsync(new Runnable() {
        @Override
        public void run() {
            HttpURLConnection urlConnection = buildURLConnection();

            // Get request body now if there's a provider
            if (bodyProvider != null) {
                body = bodyProvider.getRequestBody();
            }

            // Update socket factory as needed
            if (urlConnection instanceof HttpsURLConnection) {
                HttpsURLConnection httpsURLConnection = (HttpsURLConnection) urlConnection;

                try {
                    httpsURLConnection.setSSLSocketFactory(new FlexibleSSLSocketFactory(trustStore,
                            trustStorePassword, keyStore, keyStorePassword, !verifySSL));
                } catch (GeneralSecurityException e) {
                    e.printStackTrace();
                    onRequestError(HTTPRequestError.SECURITY_EXCEPTION);
                    onRequestTerminated();
                    return; // Terminate now
                } catch (IOException e) {
                    e.printStackTrace();
                    onRequestError(HTTPRequestError.KEYSTORE_INVALID);
                    onRequestTerminated();
                    return; // Terminate now
                }

                if (!verifySSL) {
                    httpsURLConnection.setHostnameVerifier(new NoVerifyHostnameVerifier());
                    log("SSL Verification Disabled", "**********");
                }
            }

            log("Endpoint", urlConnection.getURL().toString());
            Iterator<Map.Entry<String, String>> iterator = headers.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, String> pair = (Map.Entry) iterator.next();
                urlConnection.addRequestProperty(pair.getKey(), pair.getValue());
                log("Request Header", pair.getKey() + ": " + pair.getValue());
            }
            if (multiPartContent != null) {
                log("Multipart Request Boundary", multiPartContent.getBoundary());
                int counter = 1;
                for (MultiPartContent.Part part : multiPartContent.getParts()) {
                    log("Request Body Part " + counter,
                            "Name: " + part.getName() + "; File Name: " + part.getFileName());

                    Iterator<Map.Entry<String, String>> it = part.getHeaders().entrySet().iterator();
                    while (it.hasNext()) {
                        Map.Entry<String, String> pair = (Map.Entry) it.next();
                        log("Request Body Part " + counter + " Header", pair.getKey() + ": " + pair.getValue());
                    }
                }
            } else {
                log("Request Body", body);
            }

            if (mockResponse == null) {
                // Trigger pre-execute since preparations are complete
                onPreExecute();

                // Write our request body
                try {
                    if (multiPartContent != null) {
                        multiPartContent.write(urlConnection.getOutputStream());
                    } else if (body != null) {
                        OutputStream os = urlConnection.getOutputStream();
                        OutputStreamWriter writer = new OutputStreamWriter(os);
                        writer.write(body);
                        writer.flush();
                        writer.close();
                        os.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    onRequestError(HTTPRequestError.OTHER);
                    onRequestTerminated();
                    return; // Terminate now
                }

                // Get the response
                InputStream content;
                try {
                    content = urlConnection.getInputStream();
                    onPostExecute();
                } catch (SocketTimeoutException e) { // Timeout
                    e.printStackTrace();
                    onPostExecute();
                    onRequestError(HTTPRequestError.TIMEOUT);
                    onRequestTerminated();
                    return; // Terminate now
                } catch (IOException e) { // All other exceptions
                    e.printStackTrace();
                    content = urlConnection.getErrorStream();
                    onPostExecute();
                }

                // Pre-process the response
                final HTTPResponse response = HTTPResponse.from(HTTPRequest.this, urlConnection, content);

                if (response.isConnectionError()) {
                    onRequestError(HTTPRequestError.OTHER);
                    onRequestTerminated();
                    return; // Terminate now
                }

                // Log response
                log("Response Message", response.getResponseMessage());
                log("Response Content", response.getStringContent());

                // Trigger request completed and return the response
                onRequestCompleted(response);

                // Terminate the connection
                urlConnection.disconnect();

                onRequestTerminated();
            } else {
                onPreExecute();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                onPostExecute();
                log("Response Message", mockResponse.getResponseMessage());
                log("Response Content", mockResponse.getStringContent());
                onRequestCompleted(mockResponse);
                urlConnection.disconnect();
                onRequestTerminated();
            }
        }
    });
    return this;
}

From source file:com.athena.peacock.agent.netty.PeacockClientHandler.java

@SuppressWarnings("unchecked")
@Override//from  w w w  .  j a v  a  2 s  .  c o m
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    logger.debug("channelRead0() has invoked.");

    logger.debug("[Client] Object => " + msg.getClass().getName());
    logger.debug("[Client] Contents => " + msg.toString());

    if (msg instanceof PeacockDatagram) {
        MessageType messageType = ((PeacockDatagram<?>) msg).getMessageType();

        if (messageType.equals(MessageType.COMMAND)) {
            ProvisioningResponseMessage response = new ProvisioningResponseMessage();
            response.setAgentId(((PeacockDatagram<ProvisioningCommandMessage>) msg).getMessage().getAgentId());
            response.setBlocking(((PeacockDatagram<ProvisioningCommandMessage>) msg).getMessage().isBlocking());

            ((PeacockDatagram<ProvisioningCommandMessage>) msg).getMessage().executeCommands(response);

            ctx.writeAndFlush(new PeacockDatagram<ProvisioningResponseMessage>(response));
        } else if (messageType.equals(MessageType.PACKAGE_INFO)) {
            ctx.writeAndFlush("Start OS Package collecting...");

            String packageFile = null;

            try {
                packageFile = PropertyUtil.getProperty(PeacockConstant.PACKAGE_FILE_KEY);
            } catch (Exception e) {
                // nothing to do.
            } finally {
                if (StringUtils.isEmpty(packageFile)) {
                    packageFile = "/peacock/agent/config/package.log";
                }
            }

            new PackageGatherThread(ctx, packageFile).start();
        } else if (messageType.equals(MessageType.INITIAL_INFO)) {
            machineId = ((PeacockDatagram<AgentInitialInfoMessage>) msg).getMessage().getAgentId();
            String packageCollected = ((PeacockDatagram<AgentInitialInfoMessage>) msg).getMessage()
                    .getPackageCollected();
            String softwareInstalled = ((PeacockDatagram<AgentInitialInfoMessage>) msg).getMessage()
                    .getSoftwareInstalled();

            String agentFile = null;
            String agentId = null;

            try {
                agentFile = PropertyUtil.getProperty(PeacockConstant.AGENT_ID_FILE_KEY);
            } catch (Exception e) {
                // nothing to do.
            } finally {
                if (StringUtils.isEmpty(agentFile)) {
                    agentFile = "/peacock/agent/.agent";
                }
            }

            File file = new File(agentFile);
            boolean isNew = false;

            try {
                agentId = IOUtils.toString(file.toURI());

                if (!agentId.equals(machineId)) {
                    isNew = true;
                }
            } catch (IOException e) {
                logger.error(agentFile + " file cannot read or saved invalid agent ID.", e);
            }

            if (isNew) {
                logger.info("New Agent-ID({}) will be saved.", machineId);

                try {
                    file.setWritable(true);
                    OutputStreamWriter output = new OutputStreamWriter(new FileOutputStream(file));
                    output.write(machineId);
                    file.setReadOnly();
                    IOUtils.closeQuietly(output);
                } catch (UnsupportedEncodingException e) {
                    logger.error("UnsupportedEncodingException has occurred : ", e);
                } catch (FileNotFoundException e) {
                    logger.error("FileNotFoundException has occurred : ", e);
                } catch (IOException e) {
                    logger.error("IOException has occurred : ", e);
                }
            }

            //   ?      ??   
            if (packageCollected != null && packageCollected.equals("N")) {
                if (!_packageCollected) {
                    _packageCollected = true;
                    String packageFile = null;

                    try {
                        packageFile = PropertyUtil.getProperty(PeacockConstant.PACKAGE_FILE_KEY);
                    } catch (Exception e) {
                        // nothing to do.
                    } finally {
                        if (StringUtils.isEmpty(packageFile)) {
                            packageFile = "/peacock/agent/config/package.log";
                        }
                    }

                    file = new File(packageFile);

                    if (!file.exists()) {
                        new PackageGatherThread(ctx, packageFile).start();
                    }
                }
            }

            if (softwareInstalled != null && softwareInstalled.equals("N")) {
                if (!_softwareCollected) {
                    _softwareCollected = true;
                    new SoftwareGatherThread(ctx).start();
                }
            }

            Scheduler scheduler = (Scheduler) AppContext.getBean("quartzJobScheduler");

            if (!scheduler.isStarted()) {
                scheduler.start();
            }
        }
    }
}

From source file:com.googlecode.CallerLookup.Main.java

public void doUpdate() {
    showDialog(DIALOG_PROGRESS);//  w  w w .  ja  v a2s.c  om
    savePreferences();
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                URL uri = new URL(UPDATE_URL);
                URLConnection urlc = uri.openConnection();
                long lastModified = urlc.getLastModified();
                if ((lastModified == 0) || (lastModified != mPrefs.getLong(PREFS_UPDATE, 0))) {
                    FileOutputStream file = getApplicationContext().openFileOutput(UPDATE_FILE, MODE_PRIVATE);
                    OutputStreamWriter content = new OutputStreamWriter(file);

                    String tmp;
                    InputStream is = urlc.getInputStream();
                    BufferedReader br = new BufferedReader(new InputStreamReader(is));
                    while ((tmp = br.readLine()) != null) {
                        content.write(tmp + "\n");
                    }

                    content.flush();
                    content.close();
                    file.close();

                    SharedPreferences.Editor prefsEditor = mPrefs.edit();
                    prefsEditor.putLong(PREFS_UPDATE, lastModified);
                    prefsEditor.commit();

                    Message message = mUpdateHandler.obtainMessage();
                    message.what = MESSAGE_UPDATE_FINISHED;
                    mUpdateHandler.sendMessage(message);
                } else {
                    Message message = mUpdateHandler.obtainMessage();
                    message.what = MESSAGE_UPDATE_UNNECESSARY;
                    mUpdateHandler.sendMessage(message);
                }
            } catch (MalformedURLException e) {
                System.out.println(e.getMessage());
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }
    }).start();
}

From source file:davmail.exchange.ews.EWSMethod.java

protected byte[] generateSoapEnvelope() {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {/*from ww w  .  jav  a  2 s .c o m*/
        OutputStreamWriter writer = new OutputStreamWriter(baos, "UTF-8");
        writer.write("<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" "
                + "xmlns:t=\"http://schemas.microsoft.com/exchange/services/2006/types\" "
                + "xmlns:m=\"http://schemas.microsoft.com/exchange/services/2006/messages\">" + "");
        writer.write("<soap:Header>");
        if (serverVersion != null) {
            writer.write("<t:RequestServerVersion Version=\"");
            writer.write(serverVersion);
            writer.write("\"/>");
        }
        if (timezoneContext != null) {
            writer.write("<t:TimeZoneContext><t:TimeZoneDefinition Id=\"");
            writer.write(timezoneContext);
            writer.write("\"/></t:TimeZoneContext>");
        }
        writer.write("</soap:Header>");

        writer.write("<soap:Body>");
        writer.write("<m:");
        writer.write(methodName);
        if (traversal != null) {
            traversal.write(writer);
        }
        if (deleteType != null) {
            deleteType.write(writer);
        }
        if (methodOptions != null) {
            for (AttributeOption attributeOption : methodOptions) {
                attributeOption.write(writer);
            }
        }
        writer.write(">");
        writeSoapBody(writer);
        writer.write("</m:");
        writer.write(methodName);
        writer.write(">");
        writer.write("</soap:Body>" + "</soap:Envelope>");
        writer.flush();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return baos.toByteArray();
}

From source file:TargetsAPI.java

/**
 * Send the POST request to the Wikitude Cloud Targets API.
 * /*from w  w w .  jav a2  s. c  o m*/
 * <b>Remark</b>: We are not using any external libraries for sending HTTP
 * requests, to be as independent as possible. Libraries like Apache
 * HttpComponents (included in Android already) make it a lot easier to
 * interact with HTTP connections.
 * 
 * @param body
 *            The JSON body that is sent in the request.
 * @return The response from the server, in JSON format
 * 
 * @throws IOException
 *             when the server cannot serve the request for any reason, or
 *             anything went wrong during the communication between client
 *             and server.
 * 
 */
private String sendRequest(String body) throws IOException {

    BufferedReader reader = null;
    OutputStreamWriter writer = null;

    try {

        // create the URL object from the endpoint
        URL url = new URL(API_ENDPOINT);

        // open the connection
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // use POST and configure the connection
        connection.setRequestMethod("POST");
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);

        // set the request headers
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("X-Api-Token", apiToken);
        connection.setRequestProperty("X-Version", "" + apiVersion);
        connection.setRequestProperty("Content-Length", String.valueOf(body.length()));

        // construct the writer and write request
        writer = new OutputStreamWriter(connection.getOutputStream());
        writer.write(body);
        writer.flush();

        // listen on the server response
        reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

        // construct the server response and return
        StringBuilder sb = new StringBuilder();
        for (String line; (line = reader.readLine()) != null;) {
            sb.append(line);
        }

        // return the result
        return sb.toString();

    } catch (MalformedURLException e) {
        // the URL we specified as endpoint was not valid
        System.err.println("The URL " + API_ENDPOINT + " is not a valid URL");
        e.printStackTrace();
        return null;
    } catch (ProtocolException e) {
        // this should not happen, it means that we specified a wrong
        // protocol
        System.err.println("The HTTP method is not valid. Please check if you specified POST.");
        e.printStackTrace();
        return null;
    } finally {
        // close the reader and writer
        try {
            writer.close();
        } catch (Exception e) {
            // intentionally left blank
        }
        try {
            reader.close();
        } catch (Exception e) {
            // intentionally left blank
        }
    }
}

From source file:com.example.abrahamsofer.ident.Camera2Fragment.java

public void sendText() throws UnsupportedEncodingException {
    // Get user defined values
    // Create data variable for sent values to server

    JSONObject toSend = new JSONObject();
    try {/*from   w  ww .  j ava  2 s. c  om*/
        toSend.put("Price", price);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    String text = "";
    BufferedReader reader = null;

    // Send data
    try {
        // Defined URL  where to send data
        URL url = new URL(serverAddress);
        // Send POST data request

        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(toSend.toString());
        wr.flush();

        // Get the server response

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

        // Read Server Response
        while ((line = reader.readLine()) != null) {
            // Append server response in string
            sb.append(line + "\n");
        }

        text = sb.toString();
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {

            reader.close();
        }

        catch (Exception ex) {
        }
    }

    // Show response on activity

}

From source file:com.common.log.newproxy.BizStaticFileAppender.java

/**
 * ???/*from   ww w .jav a  2  s .  c o  m*/
 * @param event LoggingEvent
 * @return boolean ?
 */
private boolean log2extraFile(LoggingEvent event) {
    //?
    boolean hasLog = false;

    //StringBuffer lastDay=new StringBuffer();
    if (inCheckTrap() && event != null) {
        Object msg = event.getMessage();
        boolean needAppendExtra = isLog2Extra(msg);
        if (needAppendExtra) {//??
            String statPath = LogHelper.getLogRootPath() + FILE_SEP + "log" + FILE_SEP + CHECKFILE_PATH
                    + FILE_SEP;
            File path = new File(statPath);
            if (!path.exists()) {
                path.mkdir();
            }

            String extraFileName = getExtraLogFileName();
            extFile = new File(path, extraFileName);
            OutputStreamWriter exSw;
            FileOutputStream exFw;
            try {
                if (extFile.exists()) {//
                    exFw = new FileOutputStream(extFile, true);
                } else {//
                    exFw = new FileOutputStream(extFile);
                }
                exSw = new OutputStreamWriter(exFw, encoding);
                if (msg instanceof String) {
                    exSw.write((String) msg + NEXT_LINE);
                    hasLog = true;
                } else if (msg instanceof BizLogContent) {
                    String content = ((BizLogContent) msg).toString();
                    exSw.write(content + NEXT_LINE);
                    hasLog = true;
                }
                exSw.flush();
                exFw.flush();
                exSw.close();
                exFw.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }

        }
    }
    return hasLog;
}