Example usage for java.net HttpURLConnection setDoInput

List of usage examples for java.net HttpURLConnection setDoInput

Introduction

In this page you can find the example usage for java.net HttpURLConnection 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.vishnuvalleru.travelweatheralertsystem.MainActivity.java

private void fetchData() {

    StringBuilder urlString = new StringBuilder();

    urlString.append("http://maps.google.com/maps/api/directions/xml?origin=");
    urlString.append(src_lat);//from  ww  w. jav a2  s .c  o  m
    urlString.append(",");
    urlString.append(src_long);
    urlString.append("&destination=");// to
    urlString.append(dest_lat);
    urlString.append(",");
    urlString.append(dest_long);
    urlString.append("&sensor=true&mode=driving");

    HttpURLConnection urlConnection = null;
    URL url = null;
    try {
        url = new URL(urlString.toString());
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.connect();
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        doc = (Document) db.parse(urlConnection.getInputStream());// Util.XMLfromString(response);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    }
}

From source file:edu.pdx.cecs.orcycle.UserInfoUploader.java

boolean uploadUserInfoV4() {
    boolean result = false;
    final String postUrl = mCtx.getResources().getString(R.string.post_url);

    try {//from  w  ww.  jav  a  2 s . c o m
        JSONArray userResponses = getUserResponsesJSON();

        URL url = new URL(postUrl);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true); // Allow Inputs
        conn.setDoOutput(true); // Allow Outputs
        conn.setUseCaches(false); // Don't use a Cached Copy
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("ENCTYPE", "multipart/form-data");
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        conn.setRequestProperty("Cycleatl-Protocol-Version", "4");

        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
        JSONObject jsonUser;
        if (null != (jsonUser = getUserJSON())) {
            try {
                String deviceId = userId;

                dos.writeBytes(fieldSep + ContentField("user") + jsonUser.toString() + "\r\n");
                dos.writeBytes(
                        fieldSep + ContentField("version") + String.valueOf(kSaveProtocolVersion4) + "\r\n");
                dos.writeBytes(fieldSep + ContentField("device") + deviceId + "\r\n");
                dos.writeBytes(fieldSep + ContentField("userResponses") + userResponses.toString() + "\r\n");
                dos.writeBytes(fieldSep);
                dos.flush();
            } catch (Exception ex) {
                Log.e(MODULE_TAG, ex.getMessage());
                return false;
            } finally {
                dos.close();
            }
            int serverResponseCode = conn.getResponseCode();
            String serverResponseMessage = conn.getResponseMessage();
            // JSONObject responseData = new JSONObject(serverResponseMessage);
            Log.v("Jason", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
            if (serverResponseCode == 201 || serverResponseCode == 202) {
                // TODO: Record somehow that data was uploaded successfully
                result = true;
            }
        } else {
            result = false;
        }
    } catch (IllegalStateException e) {
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } catch (JSONException e) {
        e.printStackTrace();
        return false;
    }
    return result;
}

From source file:com.adr.taskexecutor.ui.TaskExecutorRemote.java

@Override
public void run(TaskExecutor.RunProcess ui) throws Exception {

    URL url;//from   w ww .ja v  a 2  s  . c om
    BufferedReader readerin = null;
    Writer writerout = null;
    try {
        // http://localhost:8084/taskexecutor/executetask?parameter=&loglevel=INFO&trace=false&stats=true&task=
        url = new URL(jURL.getText());

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setRequestMethod("POST");
        connection.setAllowUserInteraction(false);

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

        String query = "&parameter=" + URLEncoder.encode(parameter, "UTF-8");
        query += "&task=" + URLEncoder.encode(task, "UTF-8");
        query += "&language=" + URLEncoder.encode(language, "UTF-8");
        query += "&loglevel=" + URLEncoder.encode(jLoggingLevel.getSelectedItem().toString(), "UTF-8");
        query += "&trace=" + URLEncoder.encode(Boolean.toString(jTrace.isSelected()), "UTF-8");
        query += "&stats=" + URLEncoder.encode(Boolean.toString(jStats.isSelected()), "UTF-8");

        writerout = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
        writerout.write("Content-Type: application/x-www- form-urlencoded,encoding=UTF-8\n");
        writerout.write("Content-length: " + String.valueOf(query.length()) + "\n");
        writerout.write("\n");
        writerout.write(query);
        writerout.flush();

        writerout.close();
        writerout = null;

        int responsecode = connection.getResponseCode();
        if (responsecode == HttpURLConnection.HTTP_OK) {
            StringBuilder text = new StringBuilder();

            readerin = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line = null;
            while ((line = readerin.readLine()) != null) {
                text.append(line);
                text.append(System.getProperty("line.separator"));
            }

            JSONParser jsonp = new JSONParser();
            JSONObject json = (JSONObject) jsonp.parse(text.toString());

            // Print lines
            JSONArray jsonlines = (JSONArray) json.get("lines");
            for (Object l : jsonlines) {
                JSONObject jsonline = (JSONObject) l;
                Object type = jsonline.get("type");
                if ("build".equals(type)) {
                    ui.buildMessage((String) jsonline.get("text"));
                } else if ("run".equals(type)) {
                    ui.runMessage((String) jsonline.get("text"));
                } else if ("out".equals(type)) {
                    ui.printOut((String) jsonline.get("text"));
                } else if ("log".equals(type)) {
                    ui.printLog((String) jsonline.get("text"));
                } else if ("success".equals(type)) {
                    ui.successMessage(((Number) jsonline.get("time")).longValue());
                } else if ("fail".equals(type)) {
                    ui.failMessage((String) jsonline.get("text"), ((Number) jsonline.get("time")).longValue());
                } else if ("exception".equals(type)) {
                    ui.exceptionMessage((String) jsonline.get("text"),
                            ((Number) jsonline.get("time")).longValue());
                }
            }

            // Print stats
            ui.getStatsModel().reset();
            JSONArray jsonstats = (JSONArray) json.get("stats");
            if (jsonstats != null) {
                for (Object l : jsonstats) {
                    JSONObject jsonstat = (JSONObject) l;
                    ui.getStatsModel().addRow((String) jsonstat.get("task"), (String) jsonstat.get("step"),
                            ((Number) jsonstat.get("executions")).intValue(),
                            ((Number) jsonstat.get("records")).intValue(),
                            ((Number) jsonstat.get("rejected")).intValue(),
                            ((Number) jsonstat.get("totaltime")).doubleValue(),
                            ((Number) jsonstat.get("avgtime")).doubleValue());
                }
            }

            // save preferences if execution went well
            Configuration.getInstance().setPreference("remote.serverurl", jURL.getText());
            Configuration.getInstance().setPreference("remote.logginglevel",
                    jLoggingLevel.getSelectedItem().toString());
            Configuration.getInstance().setPreference("remote.trace", Boolean.toString(jTrace.isSelected()));
            Configuration.getInstance().setPreference("remote.stats", Boolean.toString(jStats.isSelected()));
            Configuration.getInstance().flushPreferences();

            //                 } catch (NullPointerException ex) {
            //                 } catch (ClassCastException ex) {
            //                 } catch (ParseException ex) {
        } else {
            throw new IOException(MessageFormat.format(bundle.getString("message.httperror"),
                    Integer.toString(responsecode), connection.getResponseMessage()));
        }
        //        } catch (MalformedURLException ex) {
        //        } catch (IOException ex) {
    } finally {
        if (writerout != null) {
            try {
                writerout.close();
            } catch (IOException ex) {
            }
            writerout = null;
        }
        if (readerin != null) {
            try {
                readerin.close();
            } catch (IOException ex) {
            }
            readerin = null;
        }
    }
}

From source file:csic.ceab.movelab.beepath.Util.java

public static boolean uploadFile(byte[] bytes, String filename, String uploadurl) {

    HttpURLConnection conn = null;
    DataOutputStream dos = null;//  w  w w.  j av a2s .  com
    // DataInputStream inStream = null;

    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";

    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 64 * 1024; // old value 1024*1024
    ByteArrayInputStream byteArrayInputStream = null;
    boolean isSuccess = true;
    try {
        // ------------------ CLIENT REQUEST

        byteArrayInputStream = new ByteArrayInputStream(bytes);

        // open a URL connection to the Servlet
        URL url = new URL(uploadurl);
        // Open a HTTP connection to the URL
        conn = (HttpURLConnection) url.openConnection();
        // Allow Inputs
        conn.setDoInput(true);
        // Allow Outputs
        conn.setDoOutput(true);
        // Don't use a cached copy.
        conn.setUseCaches(false);
        // set timeout
        conn.setConnectTimeout(60000);
        conn.setReadTimeout(60000);
        // Use a post method.
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

        dos = new DataOutputStream(conn.getOutputStream());
        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + filename + "\""
                + lineEnd);
        dos.writeBytes(lineEnd);

        // create a buffer of maximum size
        bytesAvailable = byteArrayInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];

        // read file and write it into form...
        bytesRead = byteArrayInputStream.read(buffer, 0, bufferSize);
        while (bytesRead > 0) {
            dos.write(buffer, 0, bufferSize);
            bytesAvailable = byteArrayInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = byteArrayInputStream.read(buffer, 0, bufferSize);
        }

        // send multipart form data necesssary after file data...
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

        // close streams
        // Log.e(TAG,"UploadService Runnable:File is written");
        // fileInputStream.close();
        // dos.flush();
        // dos.close();
    } catch (Exception e) {
        // Log.e(TAG, "UploadService Runnable:Client Request error", e);
        isSuccess = false;
    } finally {
        if (dos != null) {
            try {
                dos.close();
            } catch (IOException e) {
                // Log.e(TAG, "exception" + e);

            }
        }
        if (byteArrayInputStream != null) {
            try {
                byteArrayInputStream.close();
            } catch (IOException e) {
                // Log.e(TAG, "exception" + e);

            }
        }

    }

    // ------------------ read the SERVER RESPONSE
    try {

        if (conn.getResponseCode() != 200) {
            isSuccess = false;
        }
    } catch (IOException e) {
        // Log.e(TAG, "Connection error", e);
        isSuccess = false;
    }

    return isSuccess;
}

From source file:com.forecast.io.toolbox.NetworkServiceTask.java

@Override
protected INetworkResponse doInBackground(INetworkRequest... params) {
    INetworkRequest request = params[0];

    if (request == null || isCancelled()) {
        return null;
    }//from   w  w  w. j  a v a2  s.co m

    InputStream input = null;

    BufferedOutputStream output = null;

    HttpURLConnection connection = null;

    INetworkResponse response = null;

    try {
        response = (INetworkResponse) request.getResponse().newInstance();

        URL url = new URL(request.getUri().toString());

        connection = (HttpURLConnection) url.openConnection();

        connection.setReadTimeout(SOCKET_TIME_OUT);

        connection.setConnectTimeout(CONNECTION_TIME_OUT);

        connection.setRequestMethod(request.getMethod().toString());

        connection.setDoInput(true);

        if (NetworkUtils.Method.POST.equals(request.getMethod())) {
            String data = request.getPostBody();

            if (data != null) {
                connection.setDoOutput(true);

                connection.setRequestProperty("Content-Type", request.getContentType());

                output = new BufferedOutputStream(connection.getOutputStream());

                output.write(data.getBytes());

                output.flush();

                IOUtils.closeQuietly(output);
            }
        }

        int code = connection.getResponseCode();

        input = (code != HttpStatus.SC_OK) ? connection.getErrorStream() : connection.getInputStream();

        response.onNetworkResponse(new JSONObject(IOUtils.toString(input)));

        IOUtils.closeQuietly(input);
    } catch (Exception e) {
        Log.e(Constants.LOG_TAG, e.toString());
    } finally {
        if (connection != null) {
            connection.disconnect();
        }

        IOUtils.closeQuietly(input);

        IOUtils.closeQuietly(output);
    }

    return response;
}

From source file:com.mercandalli.android.apps.files.common.net.TaskPost.java

@Override
protected String doInBackground(Void... urls) {

    try {/* w  w w .  ja v  a 2s .c o m*/
        if (this.mParameters != null) {
            if (!StringUtils.isNullOrEmpty(Config.getNotificationId())) {
                mParameters.add(new StringPair("android_id", "" + Config.getNotificationId()));
            }
            url = NetUtils.addUrlParameters(url, mParameters);
        }

        Log.d("TaskGet", "url = " + url);

        final URL tmpUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) tmpUrl.openConnection();
        conn.setReadTimeout(10_000);
        conn.setConnectTimeout(15_000);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Authorization", "Basic " + Config.getUserToken());
        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);

        if (this.mParameters != null) {
            final OutputStream outputStream = conn.getOutputStream();
            final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            writer.write(getQuery(mParameters));
            writer.flush();
            writer.close();
            outputStream.close();
        }

        conn.connect(); // Starts the query
        int responseCode = conn.getResponseCode();
        InputStream inputStream = new BufferedInputStream(conn.getInputStream());

        // convert inputstream to string
        String resultString = convertInputStreamToString(inputStream);

        //int responseCode = response.getStatusLine().getStatusCode();
        if (responseCode >= 300) {
            resultString = "Status Code " + responseCode + ". " + resultString;
        }

        conn.disconnect();

        return resultString;
    } catch (IOException e) {
        Log.e(getClass().getName(), "Failed to convert Json", e);
    }
    return null;

    //        try {
    //
    //            // http://stackoverflow.com/questions/9767952/how-to-add-parameters-to-httpurlconnection-using-post
    //
    //            HttpPost httppost = new HttpPost(url);
    //
    //            MultipartEntity mpEntity = new MultipartEntity();
    //            if (this.file != null) mpEntity.addPart("file", new FileBody(file, "*/*"));
    //
    //            String log_parameters = "";
    //            if (this.parameters != null)
    //                for (StringPair b : parameters) {
    //                    mpEntity.addPart(b.getName(), new StringBody(b.getValue(), Charset.forName("UTF-8")));
    //                    log_parameters += b.getName() + ":" + b.getValue() + " ";
    //                }
    //            Log.d("TaskPost", "url = " + url + " " + log_parameters);
    //
    //            httppost.setEntity(mpEntity);
    //
    //            StringBuilder authentication = new StringBuilder().append(app.getConfig().getUser().getAccessLogin()).append(":").append(app.getConfig().getUser().getAccessPassword());
    //            String result = Base64.encodeBytes(authentication.toString().getBytes());
    //            httppost.setHeader("Authorization", "Basic " + result);
    //
    //            HttpClient httpclient = new DefaultHttpClient();
    //            HttpResponse response = httpclient.execute(httppost);
    //
    //            // receive response as inputStream
    //            InputStream inputStream = response.getEntity().getContent();
    //
    //            String resultString = null;
    //
    //            // convert inputstream to string
    //            if (inputStream != null)
    //                resultString = convertInputStreamToString(inputStream);
    //
    //            int responseCode = response.getStatusLine().getStatusCode();
    //            if (responseCode >= 300)
    //                resultString = "Status Code " + responseCode + ". " + resultString;
    //            return resultString;
    //
    //
    //        } catch (UnsupportedEncodingException e) {
    //            e.printStackTrace();
    //        } catch (ClientProtocolException e) {
    //            e.printStackTrace();
    //        } catch (IOException e) {
    //            e.printStackTrace();
    //        }
    //        return null;
}

From source file:org.jmxtrans.embedded.output.LibratoWriter.java

/**
 * Send given metrics to the Graphite server.
 *//*w ww.  ja  v  a  2 s  .  c  o m*/
@Override
public void write(Iterable<QueryResult> results) {
    logger.debug("Export to '{}', proxy {} metrics {}", url, proxy, results);

    List<QueryResult> counters = new ArrayList<QueryResult>();
    List<QueryResult> gauges = new ArrayList<QueryResult>();
    for (QueryResult result : results) {
        if (METRIC_TYPE_GAUGE.equals(result.getType())) {
            gauges.add(result);
        } else if (METRIC_TYPE_COUNTER.equals(result.getType())) {
            counters.add(result);
        } else if (null == result.getType()) {
            logger.info("Unspecified type for result {}, export it as counter");
            counters.add(result);
        } else {
            logger.info("Unsupported metric type '{}' for result {}, export it as counter", result.getType(),
                    result);
            counters.add(result);
        }
    }

    HttpURLConnection urlConnection = null;
    try {
        if (proxy == null) {
            urlConnection = (HttpURLConnection) url.openConnection();
        } else {
            urlConnection = (HttpURLConnection) url.openConnection(proxy);
        }
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setReadTimeout(libratoApiTimeoutInMillis);
        urlConnection.setRequestProperty("content-type", "application/json; charset=utf-8");
        urlConnection.setRequestProperty("Authorization", "Basic " + basicAuthentication);
        urlConnection.setRequestProperty("User-Agent", httpUserAgent);

        serialize(counters, gauges, urlConnection.getOutputStream());
        int responseCode = urlConnection.getResponseCode();
        if (responseCode != 200) {
            exceptionCounter.incrementAndGet();
            logger.warn("Failure {}:'{}' to send result to Librato server '{}' with proxy {}, user {}",
                    responseCode, urlConnection.getResponseMessage(), url, proxy, user);
        }
        if (logger.isTraceEnabled()) {
            IoUtils2.copy(urlConnection.getInputStream(), System.out);
        }
    } catch (Exception e) {
        exceptionCounter.incrementAndGet();
        logger.warn("Failure to send result to Librato server '{}' with proxy {}, user {}", url, proxy, user,
                e);
    } finally {
        if (urlConnection != null) {
            try {
                InputStream in = urlConnection.getInputStream();
                IoUtils2.copy(in, IoUtils2.nullOutputStream());
                IoUtils2.closeQuietly(in);
                InputStream err = urlConnection.getErrorStream();
                if (err != null) {
                    IoUtils2.copy(err, IoUtils2.nullOutputStream());
                    IoUtils2.closeQuietly(err);
                }
            } catch (IOException e) {
                logger.warn("Exception flushing http connection", e);
            }
        }

    }
}

From source file:com.adaptris.core.http.client.net.StandardHttpProducer.java

private HttpURLConnection configure(HttpURLConnection http, AdaptrisMessage msg) throws Exception {
    RequestMethod rm = getMethod(msg);/*from www .j a v  a 2 s  . co m*/
    log.trace("HTTP Request Method is : [{}]", rm);
    http.setRequestMethod(rm.name());
    http.setInstanceFollowRedirects(handleRedirection());
    http.setDoInput(true);
    getRequestHeaderProvider().addHeaders(msg, http);
    String contentType = getContentTypeProvider().getContentType(msg);
    if (!isEmpty(contentType)) {
        http.setRequestProperty(CONTENT_TYPE, contentType);
    }
    return http;
}

From source file:eu.codeplumbers.cosi.services.CosiFileService.java

private void getAllRemoteFolders() {
    //File.deleteAllFolders();

    URL urlO = null;/*from   w  w  w  . j  a va 2 s  .  c o m*/
    try {
        urlO = new URL(folderUrl);
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        // read the response
        int status = conn.getResponseCode();
        InputStream in = null;

        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            in = conn.getErrorStream();
        } else {
            in = conn.getInputStream();
        }

        StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "UTF-8");
        String result = writer.toString();

        JSONArray jsonArray = new JSONArray(result);

        if (jsonArray != null) {
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject folderJson = jsonArray.getJSONObject(i).getJSONObject("value");
                File file = File.getByRemoteId(folderJson.get("_id").toString());

                if (file == null) {
                    file = new File(folderJson, true);
                } else {
                    file.setName(folderJson.getString("name"));
                    file.setPath(folderJson.getString("path"));
                    file.setCreationDate(folderJson.getString("creationDate"));
                    file.setLastModification(folderJson.getString("lastModification"));
                    file.setTags(folderJson.getString("tags"));
                }

                mBuilder.setProgress(jsonArray.length(), i, false);
                mBuilder.setContentText("Indexing remote folder : " + file.getName());
                mNotifyManager.notify(notification_id, mBuilder.build());

                EventBus.getDefault()
                        .post(new FileSyncEvent(SYNC_MESSAGE, "Indexing remote folder : " + file.getName()));

                file.save();
                createFolder(file.getPath(), file.getName());

                allFiles.add(file);
            }
        } else {
            EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, "Failed to parse API response"));
            stopSelf();
        }

        in.close();
        conn.disconnect();

    } catch (MalformedURLException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (ProtocolException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (IOException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (JSONException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    }
}

From source file:com.wavemaker.runtime.service.WaveMakerService.java

public String remoteRESTCall(String remoteURL, String params, String method, String contentType) {
    proxyCheck(remoteURL);/*from   w  w w . jav a2s.  c o m*/
    String charset = "UTF-8";
    StringBuffer returnString = new StringBuffer();
    try {
        if (method.toLowerCase().equals("put") || method.toLowerCase().equals("post") || params == null
                || params.equals("")) {
        } else {
            if (remoteURL.indexOf("?") != -1) {
                remoteURL += "&" + params;
            } else {
                remoteURL += "?" + params;
            }
        }

        URL url = new URL(remoteURL);
        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Opening URL: " + url);
        }
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod(method);
        connection.setDoInput(true);
        connection.setRequestProperty("Accept-Charset", "application/json");
        connection.setRequestProperty("Accept-Encoding", "text/plain");
        connection.setRequestProperty("Content-Language", charset);
        connection.setRequestProperty("Content-Type", contentType);
        connection.setRequestProperty("Transfer-Encoding", "identity");
        connection.setUseCaches(false);

        HttpServletRequest request = RuntimeAccess.getInstance().getRequest();
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            Enumeration<String> headers = request.getHeaders(name);
            if (headers != null && !name.toLowerCase().equals("accept-encoding")
                    && !name.toLowerCase().equals("accept-charset")
                    && !name.toLowerCase().equals("content-type")) {
                while (headers.hasMoreElements()) {
                    String headerValue = headers.nextElement();
                    connection.setRequestProperty(name, headerValue);
                    if (this.logger.isDebugEnabled()) {
                        this.logger.debug("HEADER: " + name + ": " + headerValue);
                    }
                }
            }
        }

        // Re-wrap single quotes into double quotes
        String finalParams;
        if (contentType.toLowerCase().equals("application/json")) {
            finalParams = params.replace("\'", "\"");
            if (!method.toLowerCase().equals("post") && !method.toLowerCase().equals("put") && method != null
                    && !method.equals("")) {
                URLEncoder.encode(finalParams, charset);
            }
        } else {
            finalParams = params;
        }

        connection.setRequestProperty("Content-Length", "" + Integer.toString(finalParams.getBytes().length));

        // set payload
        if (method.toLowerCase().equals("post") || method.toLowerCase().equals("put") || method == null
                || method.equals("")) {
            DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
            writer.writeBytes(finalParams);
            writer.flush();
            writer.close();
        }

        InputStream response = connection.getInputStream();
        BufferedReader reader = null;
        int responseLen = 0;
        try {
            int i = 0;
            String field;
            HttpServletResponse wmResponse = RuntimeAccess.getInstance().getResponse();
            while ((field = connection.getHeaderField(i)) != null) {
                String key = connection.getHeaderFieldKey(i);
                if (key == null || field == null) {
                } else {
                    if (key.toLowerCase().equals("proxy-connection") || key.toLowerCase().equals("expires")) {
                        logger.debug("Remote server returned header of: " + key + " " + field
                                + " it was not forwarded");
                    } else if (key.toLowerCase().equals("transfer-encoding")
                            && field.toLowerCase().equals("chunked")) {
                        logger.debug("Remote server returned header of: " + key + " " + field
                                + " it was not forwarded");
                    } else if (key.toLowerCase().equals("content-length")) {
                        // do NOT use this length as return header value
                        responseLen = new Integer(field);
                    } else {
                        wmResponse.addHeader(key, field);
                    }
                }
                i++;
            }
            reader = new BufferedReader(new InputStreamReader(response, charset));
            for (String line; (line = reader.readLine()) != null;) {
                returnString.append(line);
            }
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (Exception e) {
                }
            }
        }
        connection.disconnect();
        return returnString.toString();
    } catch (Exception e) {
        logger.error("ERROR in XHR proxy call: " + e.getMessage());
        throw new WMRuntimeException(e);
    }
}