Example usage for javax.net.ssl HttpsURLConnection setDoOutput

List of usage examples for javax.net.ssl HttpsURLConnection setDoOutput

Introduction

In this page you can find the example usage for javax.net.ssl HttpsURLConnection 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:com.mb.ext.web.controller.UserController.java

/**
 * /*from ww w. j  a va2  s.  co m*/
 * get news
 * 
 */
@RequestMapping(value = "/pay", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
@ResponseBody
public ResultDTO pay(@RequestBody PayDTO payDTO, HttpServletRequest request) {
    ResultDTO resultDTO = new ResultDTO();
    PayRequest payRequest = new PayRequest();
    payRequest.setAppid(WechatConstants.APPID_VALUE);
    payRequest.setMch_id(WechatConstants.MERCHANT_ID);
    payRequest.setNonce_str(RandomStringUtils.randomAlphanumeric(32));
    payRequest.setOut_trade_no(payDTO.getOut_trade_no());
    try {
        OrderDTO orderDTO = userService.getOrderByNumber(payDTO.getOut_trade_no());
        String productName = orderDTO.getProductName();
        BigDecimal amount = orderDTO.getPreAmount();
        payRequest.setBody(productName);
        payRequest.setTotal_fee(amount.multiply(new BigDecimal(100)).intValue());
        payRequest.setSpbill_create_ip(request.getRemoteAddr());
        payRequest.setNotify_url(WechatConstants.NOTIFY_URL);
        payRequest.setTrade_type("APP");
        payRequest.setAttach("ZHONGHUANBO");
    } catch (Exception e) {
        resultDTO.setCode("1");
        resultDTO.setMessage("?");
        return resultDTO;
    }

    payRequest.setSign(getSign(payRequest));
    //xml
    XStream xstreamRes = new XStream(new XppDriver() {
        public HierarchicalStreamWriter createWriter(Writer out) {
            return new PrettyPrintWriter(out) {
                // CDATA
                boolean cdata = true;

                @SuppressWarnings("rawtypes")
                public void startNode(String name, Class clazz) {
                    super.startNode(name, clazz);
                }

                protected void writeText(QuickWriter writer, String text) {
                    if (cdata) {
                        writer.write("<![CDATA[");
                        writer.write(text);
                        writer.write("]]>");
                    } else {
                        writer.write(text);
                    }
                }
            };
        }
    });
    XStream xstreamReq = new XStream(new XppDriver() /*{
                                                     public HierarchicalStreamWriter createWriter(Writer out) {
                                                     return new PrettyPrintWriter(out) {
                                                     // CDATA
                                                     boolean cdata = true;
                                                             
                                                     @SuppressWarnings("rawtypes")
                                                     public void startNode(String name, Class clazz) {
                                                     super.startNode(name, clazz);
                                                     }
                                                             
                                                     protected void writeText(QuickWriter writer, String text) {
                                                     if (cdata) {
                                                     writer.write("<![CDATA[");
                                                     writer.write(text);
                                                     writer.write("]]>");
                                                     } else {
                                                     writer.write(text);
                                                     }
                                                     }
                                                     };
                                                     }
                                                     }*/);
    xstreamReq.alias("xml", payRequest.getClass());
    String requestXML = xstreamReq.toXML(payRequest).replace("\n", "").replace("__", "_");
    try {
        requestXML = new String(requestXML.getBytes("utf-8"), "iso-8859-1");
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
    }

    //
    BufferedReader reader = null;
    InputStream is = null;
    DataOutputStream out = null;
    StringBuffer sbf = new StringBuffer();
    String wechatResponseStr = "";
    try {
        URL url = new URL(WechatConstants.UNIFIED_ORDER_URL);
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setDoOutput(true);
        out = new DataOutputStream(connection.getOutputStream());
        out.writeBytes(requestXML);
        out.flush();

        is = connection.getInputStream();

        reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        String strRead = null;
        while ((strRead = reader.readLine()) != null) {
            sbf.append(strRead);
            sbf.append("\r\n");
        }

        wechatResponseStr = sbf.toString();
    } catch (Exception e) {
        resultDTO.setCode("1");
        resultDTO.setMessage("?");
        return resultDTO;
    } finally {
        try {
            reader.close();
            is.close();
            out.close();
        } catch (IOException e) {
            resultDTO.setCode("1");
            resultDTO.setMessage("?");
            return resultDTO;
        }

    }

    //?
    xstreamRes.alias("xml", PayResponse.class);
    PayResponse payResponse = (PayResponse) xstreamRes.fromXML(wechatResponseStr);
    //MOCK MODE
    /*PayResponse payResponse = new PayResponse();
    payResponse.setPrepay_id("WX123456789009876543211234567890");
    payResponse.setMch_id("6749328409382943");
    payResponse.setNonce_str("764932874987392");
    payResponse.setTrade_type("APP");
    payResponse.setReturn_code("SUCCESS");
    payResponse.setResult_code("SUCCESS");*/

    if ("SUCCESS".equals(payResponse.getReturn_code()) && "SUCCESS".equals(payResponse.getResult_code())) {
        payDTO.setMch_id(payResponse.getMch_id());
        payDTO.setNonce_str(payResponse.getNonce_str());
        payDTO.setPrepay_id(payResponse.getPrepay_id());
        payDTO.setTrade_type(payResponse.getTrade_type());
        payDTO.setTimestamp(String.valueOf(System.currentTimeMillis() / 1000));
        payDTO.setSign(getSignForClient(payDTO));
        resultDTO.setBody(payDTO);
        resultDTO.setCode("0");
        resultDTO.setMessage("??");
    } else {
        resultDTO.setCode("1");
        resultDTO.setMessage("?");
        return resultDTO;
    }

    return resultDTO;
}

From source file:com.dagobert_engine.core.service.MtGoxApiAdapter.java

/**
 * Queries the mtgox api with params/*w  ww. j  a  v a 2 s.c o  m*/
 * 
 * @param url
 * @return
 */
public String query(String path, HashMap<String, String> args) {

    final String publicKey = mtGoxConfig.getMtGoxPublicKey();
    final String privateKey = mtGoxConfig.getMtGoxPrivateKey();

    if (publicKey == null || privateKey == null || "".equals(publicKey) || "".equals(privateKey)) {
        throw new ApiKeysNotSetException(
                "Either public or private key of MtGox are not set. Please set them up in src/main/resources/META-INF/seam-beans.xml");
    }

    // Create nonce
    final String nonce = String.valueOf(System.currentTimeMillis()) + "000";

    HttpsURLConnection connection = null;
    String answer = null;
    try {
        // add nonce and build arg list
        args.put(ARG_KEY_NONCE, nonce);
        String post_data = buildQueryString(args);

        String hash_data = path + "\0" + post_data; // Should be correct

        // args signature with apache cryptografic tools
        String signature = signRequest(mtGoxConfig.getMtGoxPrivateKey(), hash_data);

        // build URL
        URL queryUrl = new URL(Constants.API_BASE_URL + path);
        // create and setup a HTTP connection
        connection = (HttpsURLConnection) queryUrl.openConnection();

        connection.setRequestMethod("POST");

        connection.setRequestProperty(REQ_PROP_USER_AGENT, com.dagobert_engine.core.util.Constants.APP_NAME);
        connection.setRequestProperty(REQ_PROP_REST_KEY, mtGoxConfig.getMtGoxPublicKey());
        connection.setRequestProperty(REQ_PROP_REST_SIGN, signature.replaceAll("\n", ""));

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

        // Read the response

        DataOutputStream os = new DataOutputStream(connection.getOutputStream());
        os.writeBytes(post_data);
        os.close();

        BufferedReader br = null;

        // Any error?
        int code = connection.getResponseCode();
        if (code >= 400) {
            // get error stream
            br = new BufferedReader(new InputStreamReader((connection.getErrorStream())));

            answer = toString(br);
            logger.severe("HTTP Error on queryin " + path + ": " + code + ", answer: " + answer);
            throw new MtGoxConnectionError(code, answer);

        } else {
            // get normal stream
            br = new BufferedReader(new InputStreamReader((connection.getInputStream())));
            answer = toString(br);

        }
    } catch (UnknownHostException exc) {
        throw new MtGoxConnectionError("Could not connect to MtGox. Please check your internet connection. ("
                + exc.getClass().getName() + ")");
    } catch (IllegalStateException ex) {
        throw new MtGoxConnectionError(ex);
    } catch (IOException ex) {
        throw new MtGoxConnectionError(ex);
    } finally {

        if (connection != null)
            connection.disconnect();
        connection = null;
    }

    return answer;
}

From source file:com.citrus.mobile.RESTclient.java

public JSONObject makeWithdrawRequest(String accessToken, double amount, String currency, String owner,
        String accountNumber, String ifscCode) {
    HttpsURLConnection conn;
    DataOutputStream wr = null;//from  w w w.java 2  s  .c  om
    JSONObject txnDetails = null;
    BufferedReader in = null;

    try {
        String url = urls.getString(base_url) + urls.getString(type);

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

        //add reuqest header
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Authorization", "Bearer " + accessToken);

        StringBuffer buff = new StringBuffer("amount=");
        buff.append(amount);

        buff.append("&currency=");
        buff.append(currency);

        buff.append("&owner=");
        buff.append(owner);

        buff.append("&account=");
        buff.append(accountNumber);

        buff.append("&ifsc=");
        buff.append(ifscCode);

        conn.setDoOutput(true);
        wr = new DataOutputStream(conn.getOutputStream());

        wr.writeBytes(buff.toString());
        wr.flush();

        int responseCode = conn.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + buff.toString());
        System.out.println("Response Code : " + responseCode);

        in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }

        txnDetails = new JSONObject(response.toString());

    } catch (JSONException exception) {
        exception.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try {
            if (wr != null) {
                wr.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return txnDetails;
}

From source file:me.rojo8399.placeholderapi.impl.Metrics.java

/**
 * Sends the data to the bStats server./*from w w w .  j av  a 2s. c  o m*/
 *
 * @param data
 *            The data to send.
 * @throws Exception
 *             If the request failed.
 */
private static void sendData(JsonObject data) throws Exception {
    Validate.notNull(data, "Data cannot be null");
    HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();

    // Compress the data to save bandwidth
    byte[] compressedData = compress(data.toString());

    // Add headers
    connection.setRequestMethod("POST");
    connection.addRequestProperty("Accept", "application/json");
    connection.addRequestProperty("Connection", "close");
    connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip
    // our
    // request
    connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
    connection.setRequestProperty("Content-Type", "application/json"); // We
    // send
    // our
    // data
    // in
    // JSON
    // format
    connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);

    // Send data
    connection.setDoOutput(true);
    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
    outputStream.write(compressedData);
    outputStream.flush();
    outputStream.close();

    connection.getInputStream().close(); // We don't care about the response
    // - Just send our data :)
}

From source file:com.pearson.pdn.learningstudio.core.AbstractService.java

/**
 * Performs HTTP operations using the selected authentication method
 * /*from w  w  w .j a  va  2  s .  c  o m*/
 * @param extraHeaders   Extra headers to include in the request
 * @param method   The HTTP Method to user
 * @param relativeUrl   The URL after .com (/me)
 * @param body   The body of the message
 * @return Output in the preferred data format
 * @throws IOException
 */
protected Response doMethod(Map<String, String> extraHeaders, HttpMethod method, String relativeUrl,
        String body) throws IOException {

    if (body == null) {
        body = "";
    }

    // append .xml extension when XML data format enabled.
    if (dataFormat == DataFormat.XML) {
        logger.debug("Using XML extension on route");

        String queryString = "";
        int queryStringIndex = relativeUrl.indexOf('?');
        if (queryStringIndex != -1) {
            queryString = relativeUrl.substring(queryStringIndex);
            relativeUrl = relativeUrl.substring(0, queryStringIndex);
        }

        String compareUrl = relativeUrl.toLowerCase();

        if (!compareUrl.endsWith(".xml")) {
            relativeUrl += ".xml";
        }

        if (queryStringIndex != -1) {
            relativeUrl += queryString;
        }
    }

    final String fullUrl = API_DOMAIN + relativeUrl;

    if (logger.isDebugEnabled()) {
        logger.debug("REQUEST - Method: " + method.name() + ", URL: " + fullUrl + ", Body: " + body);
    }

    URL url = new URL(fullUrl);
    Map<String, String> oauthHeaders = getOAuthHeaders(method, url, body);

    if (oauthHeaders == null) {
        throw new RuntimeException("Authentication method not selected. SEE useOAuth# methods");
    }

    if (extraHeaders != null) {
        for (String key : extraHeaders.keySet()) {
            if (!oauthHeaders.containsKey(key)) {
                oauthHeaders.put(key, extraHeaders.get(key));
            } else {
                throw new RuntimeException("Extra headers can not include OAuth headers");
            }
        }
    }

    HttpsURLConnection request = (HttpsURLConnection) url.openConnection();
    try {
        request.setRequestMethod(method.toString());

        Set<String> oauthHeaderKeys = oauthHeaders.keySet();
        for (String oauthHeaderKey : oauthHeaderKeys) {
            request.addRequestProperty(oauthHeaderKey, oauthHeaders.get(oauthHeaderKey));
        }

        request.addRequestProperty("User-Agent", getServiceIdentifier());

        if ((method == HttpMethod.POST || method == HttpMethod.PUT) && body.length() > 0) {
            if (dataFormat == DataFormat.XML) {
                request.setRequestProperty("Content-Type", "application/xml");
            } else {
                request.setRequestProperty("Content-Type", "application/json");
            }

            request.setRequestProperty("Content-Length", String.valueOf(body.getBytes("UTF-8").length));
            request.setDoOutput(true);

            DataOutputStream out = new DataOutputStream(request.getOutputStream());
            try {
                out.writeBytes(body);
                out.flush();
            } finally {
                out.close();
            }
        }

        Response response = new Response();
        response.setMethod(method.toString());
        response.setUrl(url.toString());
        response.setStatusCode(request.getResponseCode());
        response.setStatusMessage(request.getResponseMessage());
        response.setHeaders(request.getHeaderFields());

        InputStream inputStream = null;
        if (response.getStatusCode() < ResponseStatus.BAD_REQUEST.code()) {
            inputStream = request.getInputStream();
        } else {
            inputStream = request.getErrorStream();
        }

        boolean isBinary = false;
        if (inputStream != null) {
            StringBuilder responseBody = new StringBuilder();

            String contentType = request.getContentType();
            if (contentType != null) {
                if (!contentType.startsWith("text/") && !contentType.startsWith("application/xml")
                        && !contentType.startsWith("application/json")) { // assume binary
                    isBinary = true;
                    inputStream = new Base64InputStream(inputStream, true); // base64 encode
                }
            }

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            try {
                String line = null;
                while ((line = bufferedReader.readLine()) != null) {
                    responseBody.append(line);
                }
            } finally {
                bufferedReader.close();
            }

            response.setContentType(contentType);

            if (isBinary) {
                String content = responseBody.toString();
                if (content.length() == 0) {
                    response.setBinaryContent(new byte[0]);
                } else {
                    response.setBinaryContent(Base64.decodeBase64(responseBody.toString()));
                }
            } else {
                response.setContent(responseBody.toString());
            }
        }

        if (logger.isDebugEnabled()) {
            if (isBinary) {
                logger.debug("RESPONSE - binary response omitted");
            } else {
                logger.debug("RESPONSE - " + response.toString());
            }
        }

        return response;
    } finally {
        request.disconnect();
    }

}

From source file:com.dao.ShopThread.java

private HttpsURLConnection getHttpSConn(String httpsurl) throws Exception {
    // SSLContext??
    TrustManager[] tm = { new MyX509TrustManager() };
    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
    sslContext.init(null, tm, new java.security.SecureRandom());
    // SSLContextSSLSocketFactory
    SSLSocketFactory ssf = sslContext.getSocketFactory();
    // Acts like a browser
    URL obj = new URL(httpsurl);
    HttpsURLConnection conn;
    conn = (HttpsURLConnection) obj.openConnection();
    conn.setSSLSocketFactory(ssf);//from  w  ww .  j a  v a 2s  .com
    conn.setRequestMethod("GET");
    if (null != this.cookies) {
        conn.addRequestProperty("Cookie", GenericUtil.cookieFormat(this.cookies));
    }
    conn.setRequestProperty("Host", "security.5173.com");
    conn.setRequestProperty("User-Agent", USER_AGENT);
    conn.setRequestProperty("Accept", "*/*");
    conn.setRequestProperty("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
    conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    conn.setRequestProperty("Connection", "keep-alive");
    conn.setRequestProperty("Pragma", "no-cache");
    conn.setRequestProperty("Cache-Control", "no-cache");
    conn.setDoOutput(true);
    conn.setDoInput(true);
    return conn;
}

From source file:com.gmt2001.TwitchAPIv3.java

@SuppressWarnings("UseSpecificCatch")
private JSONObject GetData(request_type type, String url, String post, String oauth, boolean isJson) {
    JSONObject j = new JSONObject("{}");
    InputStream i = null;/*w  w  w.j a  v  a2s .c  o m*/
    String rawcontent = "";

    try {
        if (url.contains("?")) {
            url += "&utcnow=" + System.currentTimeMillis();
        } else {
            url += "?utcnow=" + System.currentTimeMillis();
        }

        URL u = new URL(url);
        HttpsURLConnection c = (HttpsURLConnection) u.openConnection();

        c.addRequestProperty("Accept", header_accept);

        if (isJson) {
            c.addRequestProperty("Content-Type", "application/json");
        } else {
            c.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        }

        if (!clientid.isEmpty()) {
            c.addRequestProperty("Client-ID", clientid);
        }

        if (!oauth.isEmpty()) {
            c.addRequestProperty("Authorization", "OAuth " + oauth);
        }

        c.setRequestMethod(type.name());

        c.setUseCaches(false);
        c.setDefaultUseCaches(false);
        c.setConnectTimeout(timeout);
        c.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 PhantomBotJ/2015");

        if (!post.isEmpty()) {
            c.setDoOutput(true);
        }

        c.connect();

        if (!post.isEmpty()) {
            try (OutputStream o = c.getOutputStream()) {
                IOUtils.write(post, o);
            }
        }

        String content;

        if (c.getResponseCode() == 200) {
            i = c.getInputStream();
        } else {
            i = c.getErrorStream();
        }

        if (c.getResponseCode() == 204 || i == null) {
            content = "{}";
        } else {
            content = IOUtils.toString(i, c.getContentEncoding());
        }

        rawcontent = content;

        j = new JSONObject(content);
        j.put("_success", true);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", c.getResponseCode());
        j.put("_exception", "");
        j.put("_exceptionMessage", "");
        j.put("_content", content);
    } catch (JSONException ex) {
        if (ex.getMessage().contains("A JSONObject text must begin with")) {
            j = new JSONObject("{}");
            j.put("_success", true);
            j.put("_type", type.name());
            j.put("_url", url);
            j.put("_post", post);
            j.put("_http", 0);
            j.put("_exception", "");
            j.put("_exceptionMessage", "");
            j.put("_content", rawcontent);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    } catch (NullPointerException ex) {
        com.gmt2001.Console.err.printStackTrace(ex);
    } catch (MalformedURLException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_exception", "MalformedURLException");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");
        com.gmt2001.Console.err.logStackTrace(ex);
    } catch (SocketTimeoutException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_exception", "SocketTimeoutException");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");
        com.gmt2001.Console.err.logStackTrace(ex);
    } catch (IOException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_exception", "IOException");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");
        com.gmt2001.Console.err.logStackTrace(ex);
    } catch (Exception ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_exception", "Exception [" + ex.getClass().getName() + "]");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");
        com.gmt2001.Console.err.logStackTrace(ex);
    }

    if (i != null) {
        try {
            i.close();
        } catch (IOException ex) {
            j.put("_success", false);
            j.put("_type", type.name());
            j.put("_url", url);
            j.put("_post", post);
            j.put("_http", 0);
            j.put("_exception", "IOException");
            j.put("_exceptionMessage", ex.getMessage());
            j.put("_content", "");
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    }

    return j;
}

From source file:com.dao.ShopThread.java

private HttpsURLConnection getHttpSConn(String payurl, String method, String strlength) throws Exception {
    // SSLContext??
    TrustManager[] tm = { new MyX509TrustManager() };
    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
    sslContext.init(null, tm, new java.security.SecureRandom());
    // SSLContextSSLSocketFactory
    SSLSocketFactory ssf = sslContext.getSocketFactory();
    // Acts like a browser
    URL obj = new URL(payurl);
    HttpsURLConnection conn;
    conn = (HttpsURLConnection) obj.openConnection();
    conn.setSSLSocketFactory(ssf);/*  w w  w . j  a  va2 s .c o m*/
    conn.setRequestMethod(method);
    conn.setRequestProperty("Host", "mypay.5173.com");
    conn.setRequestProperty("User-Agent", USER_AGENT);
    conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    conn.setRequestProperty("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
    conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    // conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
    conn.setRequestProperty("Referer", payurl);
    conn.setRequestProperty("Connection", "keep-alive");
    // conn.setRequestProperty("Pragma", "no-cache");
    // conn.setRequestProperty("Cache-Control", "no-cache");
    conn.setRequestProperty("Content-Length", strlength);
    conn.setDoOutput(true);
    conn.setDoInput(true);
    return conn;
}

From source file:com.citrus.mobile.RESTclient.java

public JSONObject makeSendMoneyRequest(String accessToken, CitrusUser toUser, Amount amount, String message) {
    HttpsURLConnection conn;
    DataOutputStream wr = null;//from  www  .  ja  v  a 2 s .c  om
    JSONObject txnDetails = null;
    BufferedReader in = null;

    try {
        String url = null;

        StringBuffer postDataBuff = new StringBuffer("amount=");
        postDataBuff.append(amount.getValue());

        postDataBuff.append("&currency=");
        postDataBuff.append(amount.getCurrency());

        postDataBuff.append("&message=");
        postDataBuff.append(message);

        if (!TextUtils.isEmpty(toUser.getEmailId())) {
            url = urls.getString(base_url) + urls.getString("transfer");
            postDataBuff.append("&to=");
            postDataBuff.append(toUser.getEmailId());

        } else if (!TextUtils.isEmpty(toUser.getMobileNo())) {
            url = urls.getString(base_url) + urls.getString("suspensetransfer");

            postDataBuff.append("&to=");
            postDataBuff.append(toUser.getMobileNo());

        }

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

        //add reuqest header
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Authorization", "Bearer " + accessToken);

        conn.setDoOutput(true);
        wr = new DataOutputStream(conn.getOutputStream());

        wr.writeBytes(postDataBuff.toString());
        wr.flush();

        int responseCode = conn.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + postDataBuff.toString());
        System.out.println("Response Code : " + responseCode);

        in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }

        txnDetails = new JSONObject(response.toString());

    } catch (JSONException exception) {
        exception.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try {
            if (wr != null) {
                wr.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return txnDetails;
}

From source file:com.wwpass.connection.WWPassConnection.java

private InputStream makeRequest(String method, String command, Map<String, ?> parameters)
        throws IOException, WWPassProtocolException {
    String commandUrl = SpfeURL + command + ".xml";
    //String command_url = SpfeURL + command + ".json";

    StringBuilder sb = new StringBuilder();
    URLCodec codec = new URLCodec();

    @SuppressWarnings("unchecked")
    Map<String, Object> localParams = (Map<String, Object>) parameters;

    for (Map.Entry<String, Object> entry : localParams.entrySet()) {
        sb.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
        sb.append("=");
        if (entry.getValue() instanceof String) {
            sb.append(URLEncoder.encode((String) entry.getValue(), "UTF-8"));
        } else {/*from w  w w .j  ava  2s.  c  om*/
            sb.append(new String(codec.encode((byte[]) entry.getValue())));
        }
        sb.append("&");
    }
    String paramsString = sb.toString();
    sb = null;
    if ("GET".equalsIgnoreCase(method)) {
        commandUrl += "?" + paramsString;
    } else if ("POST".equalsIgnoreCase(method)) {

    } else {
        throw new IllegalArgumentException("Method " + method + " not supported.");
    }

    HttpsURLConnection conn = null;
    try {
        URL url = new URL(commandUrl);
        conn = (HttpsURLConnection) url.openConnection();
        conn.setReadTimeout(timeoutMs);
        conn.setSSLSocketFactory(SPFEContext.getSocketFactory());
        if ("POST".equalsIgnoreCase(method)) {
            conn.setDoOutput(true);
            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
            writer.write(paramsString);
            writer.flush();
        }
        InputStream in = conn.getInputStream();
        return getReplyData(in);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("Command-parameters combination is invalid: " + e.getMessage());
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}