Example usage for org.apache.commons.httpclient.methods PostMethod setRequestBody

List of usage examples for org.apache.commons.httpclient.methods PostMethod setRequestBody

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods PostMethod setRequestBody.

Prototype

public void setRequestBody(NameValuePair[] paramArrayOfNameValuePair) throws IllegalArgumentException 

Source Link

Usage

From source file:com.cloud.network.cisco.CiscoVnmcConnectionImpl.java

private String sendRequest(String service, String xmlRequest) throws ExecutionException {
    HttpClient client = new HttpClient();
    String response = null;/*from  w  w w  .j  ava  2 s . c o m*/
    PostMethod method = new PostMethod("/xmlIM/" + service);
    method.setRequestBody(xmlRequest);

    try {
        org.apache.commons.httpclient.protocol.Protocol myhttps = new org.apache.commons.httpclient.protocol.Protocol(
                "https", new EasySSLProtocolSocketFactory(), 443);
        client.getHostConfiguration().setHost(_ip, 443, myhttps);
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            throw new Exception("Error code : " + statusCode);
        }
        response = method.getResponseBodyAsString();
    } catch (Exception e) {
        System.out.println(e.getMessage());
        throw new ExecutionException(e.getMessage());
    }
    System.out.println(response);
    return response;
}

From source file:com.taobao.diamond.sdkapi.impl.DiamondSDKManagerImpl.java

@Override
public BatchContextResult<ConfigInfoEx> batchQuery(String serverId, String groupName, List<String> dataIds) {
    // //from  w  ww .ja  v a  2 s.  c o m
    BatchContextResult<ConfigInfoEx> response = new BatchContextResult<ConfigInfoEx>();

    // listnull
    if (dataIds == null) {
        log.error("dataId list cannot be null, serverId=" + serverId + ",group=" + groupName);
        response.setSuccess(false);
        response.setStatusMsg("dataId list cannot be null");
        return response;
    }

    // dataIdlist
    StringBuilder dataIdBuilder = new StringBuilder();
    for (String dataId : dataIds) {
        dataIdBuilder.append(dataId).append(Constants.LINE_SEPARATOR);
    }
    String dataIdStr = dataIdBuilder.toString();
    // 
    if (!login(serverId)) {
        response.setSuccess(false);
        response.setStatusMsg("login fail, serverId=" + serverId);
        return response;
    }

    // HTTP method
    PostMethod post = new PostMethod("/diamond-server/admin.do?method=batchQuery");
    // 
    post.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, require_timeout);
    try {
        // 
        NameValuePair dataId_value = new NameValuePair("dataIds", dataIdStr);
        NameValuePair group_value = new NameValuePair("group", groupName);

        post.setRequestBody(new NameValuePair[] { dataId_value, group_value });

        // http
        int status = client.executeMethod(post);
        response.setStatusCode(status);
        String responseMsg = post.getResponseBodyAsString();
        response.setResponseMsg(responseMsg);

        if (status == HttpStatus.SC_OK) {
            String json = null;
            try {
                json = responseMsg;

                // json, BatchContextResult
                List<ConfigInfoEx> configInfoExList = new LinkedList<ConfigInfoEx>();
                Object resultObj = JSONUtils.deserializeObject(json, new TypeReference<List<ConfigInfoEx>>() {
                });
                if (!(resultObj instanceof List<?>)) {
                    throw new RuntimeException("batch query deserialize type error, not list, json=" + json);
                }
                List<ConfigInfoEx> resultList = (List<ConfigInfoEx>) resultObj;
                for (ConfigInfoEx configInfoEx : resultList) {
                    configInfoExList.add(configInfoEx);
                }
                response.getResult().addAll(configInfoExList);

                // , 
                response.setSuccess(true);
                response.setStatusMsg("batch query success");
                log.info("batch query success, serverId=" + serverId + ",dataIds=" + dataIdStr + ",group="
                        + groupName + ",json=" + json);
            } catch (Exception e) {
                response.setSuccess(false);
                response.setStatusMsg("batch query deserialize error");
                log.error("batch query deserialize error, serverId=" + serverId + ",dataIdStr=" + dataIdStr
                        + ",group=" + groupName + ",json=" + json, e);
            }

        } else if (status == HttpStatus.SC_REQUEST_TIMEOUT) {
            response.setSuccess(false);
            response.setStatusMsg("batch query timeout, socket timeout(ms):" + require_timeout);
            log.error("batch query timeout, socket timeout(ms):" + require_timeout + ", serverId=" + serverId
                    + ",dataIds=" + dataIdStr + ",group=" + groupName);
        } else {
            response.setSuccess(false);
            response.setStatusMsg("batch query fail, status:" + status);
            log.error("batch query fail, status:" + status + ", response:" + responseMsg + ",serverId="
                    + serverId + ",dataIds=" + dataIdStr + ",group=" + groupName);
        }
    } catch (HttpException e) {
        response.setSuccess(false);
        response.setStatusMsg("batch query http exception" + e.getMessage());
        log.error("batch query http exception, serverId=" + serverId + ",dataIds=" + dataIdStr + ",group="
                + groupName, e);
    } catch (IOException e) {
        response.setSuccess(false);
        response.setStatusMsg("batch query io exception" + e.getMessage());
        log.error("batch query io exception, serverId=" + serverId + ",dataIds=" + dataIdStr + ",group="
                + groupName, e);
    } finally {
        // 
        post.releaseConnection();
    }

    return response;
}

From source file:com.taobao.diamond.sdkapi.impl.DiamondSDKManagerImpl.java

private ContextResult processPulishByDefinedServerId(String dataId, String groupName, String context,
        String serverId) {/*w  w  w  . j a v  a  2 s.  c  om*/
    ContextResult response = new ContextResult();
    // 
    if (!login(serverId)) {
        response.setSuccess(false);
        response.setStatusMsg(",serverId");
        return response;
    }
    if (log.isDebugEnabled())
        log.debug("processPulishByDefinedServerId(" + dataId + "," + groupName + "," + context + ","
                + serverId + ")");

    String postUrl = "/diamond-server/admin.do?method=postConfig";
    PostMethod post = new PostMethod(postUrl);
    // 
    post.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, require_timeout);
    try {
        NameValuePair dataId_value = new NameValuePair("dataId", dataId);
        NameValuePair group_value = new NameValuePair("group", groupName);
        NameValuePair content_value = new NameValuePair("content", context);

        // 
        post.setRequestBody(new NameValuePair[] { dataId_value, group_value, content_value });
        // 
        ConfigInfo configInfo = new ConfigInfo();
        configInfo.setDataId(dataId);
        configInfo.setGroup(groupName);
        configInfo.setContent(context);
        if (log.isDebugEnabled())
            log.debug("ConfigInfo: " + configInfo);
        // 
        response.setConfigInfo(configInfo);
        // http
        int status = client.executeMethod(post);
        response.setReceiveResult(post.getResponseBodyAsString());
        response.setStatusCode(status);
        log.info("" + status + "," + post.getResponseBodyAsString());
        if (status == HttpStatus.SC_OK) {
            response.setSuccess(true);
            response.setStatusMsg("");
            log.info(", dataId=" + dataId + ",group=" + groupName + ",content=" + context
                    + ",serverId=" + serverId);
        } else if (status == HttpStatus.SC_REQUEST_TIMEOUT) {
            response.setSuccess(false);
            response.setStatusMsg(", :" + require_timeout + "");
            log.error(":" + require_timeout + ", dataId=" + dataId + ",group="
                    + groupName + ",content=" + context + ",serverId=" + serverId);
        } else {
            response.setSuccess(false);
            response.setStatusMsg(", :" + status);
            log.error(":" + response.getReceiveResult() + ",dataId=" + dataId + ",group="
                    + groupName + ",content=" + context + ",serverId=" + serverId);
        }
    } catch (HttpException e) {
        response.setStatusMsg("HttpException" + e.getMessage());
        log.error("HttpException: dataId=" + dataId + ",group=" + groupName + ",content=" + context
                + ",serverId=" + serverId, e);
    } catch (IOException e) {
        response.setStatusMsg("IOException" + e.getMessage());
        log.error("IOException: dataId=" + dataId + ",group=" + groupName + ",content=" + context
                + ",serverId=" + serverId, e);
    } finally {
        // 
        post.releaseConnection();
    }

    return response;
}

From source file:com.mengka.diamond.sdkapi.impl.DiamondSDKManagerImpl.java

public BatchContextResult<ConfigInfoEx> batchQuery(String serverId, String groupName, List<String> dataIds) {
    // /*from ww  w.  j a  v a 2s.  co m*/
    BatchContextResult<ConfigInfoEx> response = new BatchContextResult<ConfigInfoEx>();

    // list?null
    if (dataIds == null) {
        log.error("dataId list cannot be null, serverId=" + serverId + ",group=" + groupName);
        response.setSuccess(false);
        response.setStatusMsg("dataId list cannot be null");
        return response;
    }

    // dataIdlist????
    StringBuilder dataIdBuilder = new StringBuilder();
    for (String dataId : dataIds) {
        dataIdBuilder.append(dataId).append(Constants.LINE_SEPARATOR);
    }
    String dataIdStr = dataIdBuilder.toString();
    // 
    if (!login(serverId)) {
        response.setSuccess(false);
        response.setStatusMsg("login fail, serverId=" + serverId);
        return response;
    }

    // HTTP method
    PostMethod post = new PostMethod("/diamond-server/admin.do?method=batchQuery");
    // 
    post.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, require_timeout);
    try {
        // ?
        NameValuePair dataId_value = new NameValuePair("dataIds", dataIdStr);
        NameValuePair group_value = new NameValuePair("group", groupName);

        post.setRequestBody(new NameValuePair[] { dataId_value, group_value });

        // http??
        int status = client.executeMethod(post);
        response.setStatusCode(status);
        String responseMsg = post.getResponseBodyAsString();
        response.setResponseMsg(responseMsg);

        if (status == HttpStatus.SC_OK) {
            String json = null;
            try {
                json = responseMsg;

                // ???json, ??BatchContextResult
                List<ConfigInfoEx> configInfoExList = new LinkedList<ConfigInfoEx>();
                Object resultObj = JSONUtils.deserializeObject(json, new TypeReference<List<ConfigInfoEx>>() {
                });
                if (!(resultObj instanceof List<?>)) {
                    throw new RuntimeException("batch query deserialize type error, not list, json=" + json);
                }
                List<ConfigInfoEx> resultList = (List<ConfigInfoEx>) resultObj;
                for (ConfigInfoEx configInfoEx : resultList) {
                    configInfoExList.add(configInfoEx);
                }
                response.getResult().addAll(configInfoExList);

                // ????, ??
                response.setSuccess(true);
                response.setStatusMsg("batch query success");
                log.info("batch query success, serverId=" + serverId + ",dataIds=" + dataIdStr + ",group="
                        + groupName + ",json=" + json);
            } catch (Exception e) {
                response.setSuccess(false);
                response.setStatusMsg("batch query deserialize error");
                log.error("batch query deserialize error, serverId=" + serverId + ",dataIdStr=" + dataIdStr
                        + ",group=" + groupName + ",json=" + json, e);
            }

        } else if (status == HttpStatus.SC_REQUEST_TIMEOUT) {
            response.setSuccess(false);
            response.setStatusMsg("batch query timeout, socket timeout(ms):" + require_timeout);
            log.error("batch query timeout, socket timeout(ms):" + require_timeout + ", serverId=" + serverId
                    + ",dataIds=" + dataIdStr + ",group=" + groupName);
        } else {
            response.setSuccess(false);
            response.setStatusMsg("batch query fail, status:" + status);
            log.error("batch query fail, status:" + status + ", response:" + responseMsg + ",serverId="
                    + serverId + ",dataIds=" + dataIdStr + ",group=" + groupName);
        }
    } catch (HttpException e) {
        response.setSuccess(false);
        response.setStatusMsg("batch query http exception" + e.getMessage());
        log.error("batch query http exception, serverId=" + serverId + ",dataIds=" + dataIdStr + ",group="
                + groupName, e);
    } catch (IOException e) {
        response.setSuccess(false);
        response.setStatusMsg("batch query io exception" + e.getMessage());
        log.error("batch query io exception, serverId=" + serverId + ",dataIds=" + dataIdStr + ",group="
                + groupName, e);
    } finally {
        // ?
        post.releaseConnection();
    }

    return response;
}

From source file:cn.leancloud.diamond.sdkapi.impl.DiamondSDKManagerImpl.java

@Override
public BatchContextResult<ConfigInfoEx> batchQuery(String serverId, String groupName, List<String> dataIds) {
    // /* w ww  .j  a v  a2 s. c  o m*/
    BatchContextResult<ConfigInfoEx> response = new BatchContextResult<ConfigInfoEx>();

    // list?null
    if (dataIds == null) {
        log.error("dataId list cannot be null, serverId=" + serverId + ",group=" + groupName);
        response.setSuccess(false);
        response.setStatusMsg("dataId list cannot be null");
        return response;
    }

    // dataIdlist????
    StringBuilder dataIdBuilder = new StringBuilder();
    for (String dataId : dataIds) {
        dataIdBuilder.append(dataId).append(Constants.LINE_SEPARATOR);
    }
    String dataIdStr = dataIdBuilder.toString();
    // 
    if (!login(serverId)) {
        response.setSuccess(false);
        response.setStatusMsg("login fail, serverId=" + serverId);
        return response;
    }

    // HTTP method
    PostMethod post = new PostMethod("/diamond-server/admin.do?method=batchQuery");
    // 
    post.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, require_timeout);
    try {
        // ?
        NameValuePair dataId_value = new NameValuePair("dataIds", dataIdStr);
        NameValuePair group_value = new NameValuePair("group", groupName);

        post.setRequestBody(new NameValuePair[] { dataId_value, group_value });

        // http??
        int status = client.executeMethod(post);
        response.setStatusCode(status);
        String responseMsg = post.getResponseBodyAsString();
        response.setResponseMsg(responseMsg);

        if (status == HttpStatus.SC_OK) {
            String json = null;
            try {
                json = responseMsg;

                // ???json, ??BatchContextResult
                List<ConfigInfoEx> configInfoExList = new LinkedList<ConfigInfoEx>();
                Object resultObj = JSONUtils.deserializeObject(json, new TypeReference<List<ConfigInfoEx>>() {
                });
                if (!(resultObj instanceof List<?>)) {
                    throw new RuntimeException("batch query deserialize type error, not list, json=" + json);
                }
                List<ConfigInfoEx> resultList = (List<ConfigInfoEx>) resultObj;
                for (ConfigInfoEx configInfoEx : resultList) {
                    configInfoExList.add(configInfoEx);
                }
                response.getResult().addAll(configInfoExList);

                // ????, ??
                response.setSuccess(true);
                response.setStatusMsg("batch query success");
                log.info("batch query success, serverId=" + serverId + ",dataIds=" + dataIdStr + ",group="
                        + groupName + ",json=" + json);
            } catch (Exception e) {
                response.setSuccess(false);
                response.setStatusMsg("batch query deserialize error");
                log.error("batch query deserialize error, serverId=" + serverId + ",dataIdStr=" + dataIdStr
                        + ",group=" + groupName + ",json=" + json, e);
            }

        } else if (status == HttpStatus.SC_REQUEST_TIMEOUT) {
            response.setSuccess(false);
            response.setStatusMsg("batch query timeout, socket timeout(ms):" + require_timeout);
            log.error("batch query timeout, socket timeout(ms):" + require_timeout + ", serverId=" + serverId
                    + ",dataIds=" + dataIdStr + ",group=" + groupName);
        } else {
            response.setSuccess(false);
            response.setStatusMsg("batch query fail, status:" + status);
            log.error("batch query fail, status:" + status + ", response:" + responseMsg + ",serverId="
                    + serverId + ",dataIds=" + dataIdStr + ",group=" + groupName);
        }
    } catch (HttpException e) {
        response.setSuccess(false);
        response.setStatusMsg("batch query http exception" + e.getMessage());
        log.error("batch query http exception, serverId=" + serverId + ",dataIds=" + dataIdStr + ",group="
                + groupName, e);
    } catch (IOException e) {
        response.setSuccess(false);
        response.setStatusMsg("batch query io exception" + e.getMessage());
        log.error("batch query io exception, serverId=" + serverId + ",dataIds=" + dataIdStr + ",group="
                + groupName, e);
    } finally {
        // ?
        post.releaseConnection();
    }

    return response;
}

From source file:cn.leancloud.diamond.sdkapi.impl.DiamondSDKManagerImpl.java

private ContextResult processPulishByDefinedServerId(String dataId, String groupName, String context,
        String serverId) {//ww  w  .jav a2s.  c  om
    ContextResult response = new ContextResult();
    // 
    if (!login(serverId)) {
        response.setSuccess(false);
        response.setStatusMsg(",??serverId?");
        return response;
    }
    if (log.isDebugEnabled())
        log.debug("processPulishByDefinedServerId(" + dataId + "," + groupName + "," + context + ","
                + serverId + ")?");

    String postUrl = "/diamond-server/admin.do?method=postConfig";
    PostMethod post = new PostMethod(postUrl);
    // 
    post.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, require_timeout);
    try {
        NameValuePair dataId_value = new NameValuePair("dataId", dataId);
        NameValuePair group_value = new NameValuePair("group", groupName);
        NameValuePair content_value = new NameValuePair("content", context);

        // ?
        post.setRequestBody(new NameValuePair[] { dataId_value, group_value, content_value });
        // ?
        ConfigInfo configInfo = new ConfigInfo();
        configInfo.setDataId(dataId);
        configInfo.setGroup(groupName);
        configInfo.setContent(context);
        if (log.isDebugEnabled())
            log.debug("?ConfigInfo: " + configInfo);
        // ??
        response.setConfigInfo(configInfo);
        // http??
        int status = client.executeMethod(post);
        response.setReceiveResult(post.getResponseBodyAsString());
        response.setStatusCode(status);
        log.info("??" + status + ",?" + post.getResponseBodyAsString());
        if (status == HttpStatus.SC_OK) {
            response.setSuccess(true);
            response.setStatusMsg("???");
            log.info("???, dataId=" + dataId + ",group=" + groupName + ",content=" + context
                    + ",serverId=" + serverId);
        } else if (status == HttpStatus.SC_REQUEST_TIMEOUT) {
            response.setSuccess(false);
            response.setStatusMsg("??, :" + require_timeout + "");
            log.error("??:" + require_timeout + ", dataId="
                    + dataId + ",group=" + groupName + ",content=" + context + ",serverId=" + serverId);
        } else {
            response.setSuccess(false);
            response.setStatusMsg("??, ??:" + status);
            log.error("??:" + response.getReceiveResult() + ",dataId=" + dataId + ",group="
                    + groupName + ",content=" + context + ",serverId=" + serverId);
        }
    } catch (HttpException e) {
        response.setStatusMsg("???HttpException" + e.getMessage());
        log.error("???HttpException: dataId=" + dataId + ",group=" + groupName + ",content="
                + context + ",serverId=" + serverId, e);
    } catch (IOException e) {
        response.setStatusMsg("???IOException" + e.getMessage());
        log.error("???IOException: dataId=" + dataId + ",group=" + groupName + ",content="
                + context + ",serverId=" + serverId, e);
    } finally {
        // ?
        post.releaseConnection();
    }

    return response;
}

From source file:com.taobao.diamond.sdkapi.impl.DiamondSDKManagerImpl.java

@Override
public BatchContextResult<ConfigInfoEx> batchAddOrUpdate(String serverId, String groupName,
        Map<String, String> dataId2ContentMap) {
    // /*from   w w w . jav  a 2s.c  om*/
    BatchContextResult<ConfigInfoEx> response = new BatchContextResult<ConfigInfoEx>();

    // mapnull
    if (dataId2ContentMap == null) {
        log.error("dataId2ContentMap cannot be null, serverId=" + serverId + " ,group=" + groupName);
        response.setSuccess(false);
        response.setStatusMsg("dataId2ContentMap cannot be null");
        return response;
    }

    // dataIdcontentmap
    StringBuilder allDataIdAndContentBuilder = new StringBuilder();
    for (String dataId : dataId2ContentMap.keySet()) {
        String content = dataId2ContentMap.get(dataId);
        allDataIdAndContentBuilder.append(dataId + Constants.WORD_SEPARATOR + content)
                .append(Constants.LINE_SEPARATOR);
    }
    String allDataIdAndContent = allDataIdAndContentBuilder.toString();

    // 
    if (!login(serverId)) {
        response.setSuccess(false);
        response.setStatusMsg("login fail, serverId=" + serverId);
        return response;
    }

    // HTTP method
    PostMethod post = new PostMethod("/diamond-server/admin.do?method=batchAddOrUpdate");
    // 
    post.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, require_timeout);
    try {
        // 
        NameValuePair dataId_value = new NameValuePair("allDataIdAndContent", allDataIdAndContent);
        NameValuePair group_value = new NameValuePair("group", groupName);

        post.setRequestBody(new NameValuePair[] { dataId_value, group_value });

        // http
        int status = client.executeMethod(post);
        response.setStatusCode(status);
        String responseMsg = post.getResponseBodyAsString();
        response.setResponseMsg(responseMsg);

        if (status == HttpStatus.SC_OK) {
            String json = null;
            try {
                json = responseMsg;

                // json, BatchContextResult
                List<ConfigInfoEx> configInfoExList = new LinkedList<ConfigInfoEx>();
                Object resultObj = JSONUtils.deserializeObject(json, new TypeReference<List<ConfigInfoEx>>() {
                });
                if (!(resultObj instanceof List<?>)) {
                    throw new RuntimeException("batch write deserialize type error, not list, json=" + json);
                }
                List<ConfigInfoEx> resultList = (List<ConfigInfoEx>) resultObj;
                for (ConfigInfoEx configInfoEx : resultList) {
                    configInfoExList.add(configInfoEx);
                }
                response.getResult().addAll(configInfoExList);
                // , 
                response.setStatusMsg("batch write success");
                log.info("batch write success,serverId=" + serverId + ",allDataIdAndContent="
                        + allDataIdAndContent + ",group=" + groupName + ",json=" + json);
            } catch (Exception e) {
                response.setSuccess(false);
                response.setStatusMsg("batch write deserialize error");
                log.error("batch write deserialize error, serverId=" + serverId + ",allDataIdAndContent="
                        + allDataIdAndContent + ",group=" + groupName + ",json=" + json, e);
            }
        } else if (status == HttpStatus.SC_REQUEST_TIMEOUT) {
            response.setSuccess(false);
            response.setStatusMsg("batch write timeout, socket timeout(ms):" + require_timeout);
            log.error("batch write timeout, socket timeout(ms):" + require_timeout + ", serverId=" + serverId
                    + ",allDataIdAndContent=" + allDataIdAndContent + ",group=" + groupName);
        } else {
            response.setSuccess(false);
            response.setStatusMsg("batch write fail, status:" + status);
            log.error("batch write fail, status:" + status + ", response:" + responseMsg + ",serverId="
                    + serverId + ",allDataIdAndContent=" + allDataIdAndContent + ",group=" + groupName);
        }
    } catch (HttpException e) {
        response.setSuccess(false);
        response.setStatusMsg("batch write http exception" + e.getMessage());
        log.error("batch write http exception, serverId=" + serverId + ",allDataIdAndContent="
                + allDataIdAndContent + ",group=" + groupName, e);
    } catch (IOException e) {
        response.setSuccess(false);
        response.setStatusMsg("batch write io exception" + e.getMessage());
        log.error("batch write io exception, serverId=" + serverId + ",allDataIdAndContent="
                + allDataIdAndContent + ",group=" + groupName, e);
    } finally {
        // 
        post.releaseConnection();
    }

    return response;
}

From source file:com.baidu.qa.service.test.client.HttpReqImpl.java

/**
 * use httpclient/*w  w w.  j a va 2s.  c om*/
 * @param file
 * @param config
 * @param vargen
 * @return
 */
public Object requestHttpByHttpClient(File file, Config config, VariableGenerator vargen) {
    FileCharsetDetector det = new FileCharsetDetector();
    try {
        String oldcharset = det.guestFileEncoding(file);
        if (oldcharset.equalsIgnoreCase("UTF-8") == false)
            FileUtil.transferFile(file, oldcharset, "UTF-8");
    } catch (Exception ex) {
        log.error("[change expect file charset error]:" + ex);
    }

    Map<String, String> datalist = FileUtil.getMapFromFile(file, "=");
    if (datalist.size() <= 1) {
        return true;
    }
    if (!datalist.containsKey(Constant.KW_ITEST_HOST) && !datalist.containsKey(Constant.KW_ITEST_URL)) {
        log.error("[wrong file]:" + file.getName() + " hasn't Url");
        return null;
    }
    if (datalist.containsKey(Constant.KW_ITEST_HOST)) {
        this.url = datalist.get(Constant.KW_ITEST_HOST);
        this.hashost = true;
        datalist.remove(Constant.KW_ITEST_HOST);
    } else {
        String action = datalist.get(Constant.KW_ITEST_URL);
        if (config.getHost().lastIndexOf("/") == config.getHost().length() - 1 && action.indexOf("/") == 0) {
            action = action.substring(1);
        }
        this.url = config.getHost() + action;
        datalist.remove("itest_url");

    }
    if (datalist.containsKey(Constant.KW_ITEST_EXPECT)) {
        this.itest_expect = datalist.get(Constant.KW_ITEST_EXPECT);
        datalist.remove(Constant.KW_ITEST_EXPECT);
    }
    if (datalist.containsKey(Constant.KW_ITEST_JSON)) {
        this.itest_expect_json = datalist.get(Constant.KW_ITEST_JSON);
        datalist.remove(Constant.KW_ITEST_JSON);
    }
    parammap = datalist;
    this.config = config;

    //HttpClient
    HttpClient httpClient = new HttpClient();
    //
    httpClient.setConnectionTimeout(30000);
    httpClient.setTimeout(30000);
    httpClient.getParams().setParameter("http.protocol.content-charset", "UTF-8");
    PostMethod postMethod = new PostMethod(url);

    if (hashost == false) {
        //cookie copy
        if (config.getVariable() != null
                && config.getVariable().containsKey(Constant.V_CONFIG_VARIABLE_COOKIE)) {

            postMethod.addRequestHeader(Constant.V_CONFIG_VARIABLE_COOKIE,
                    (String) config.getVariable().get(Constant.V_CONFIG_VARIABLE_COOKIE));
            log.info("[HTTP Request Cookie]"
                    + (String) config.getVariable().get(Constant.V_CONFIG_VARIABLE_COOKIE));
        }
    }

    //??keysparams??body??key=value?
    if (parammap.size() == 1 && (parammap.containsKey("params") || parammap.containsKey("Params"))) {
        String key = "";
        if (parammap.containsKey("params")) {
            key = "params";
        } else if (parammap.containsKey("Params")) {
            key = "Params";
        }
        postMethod.setRequestHeader("Content-Type", "text/json;charset=utf-8");
        postMethod.setRequestBody(parammap.get(key).toString());
    } else {
        NameValuePair[] data = new NameValuePair[parammap.size()];
        int i = 0;
        for (Map.Entry<String, String> entry : parammap.entrySet()) {
            log.info("[HTTP post params]" + (String) entry.getKey() + ":" + (String) entry.getValue() + ";");
            if (entry.getValue().toString().contains("###")) {

            } else {
                data[i] = new NameValuePair((String) entry.getKey(), (String) entry.getValue());
            }
            i++;
        }
        // ?postMethod
        postMethod.setRequestBody(data);
    }

    Assert.assertNotNull("get request error,check the input file", postMethod);

    String response = "";
    // postMethod
    try {
        int statusCode = httpClient.executeMethod(postMethod);
        // HttpClient????POSTPUT???
        // 301302
        if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
            // ???
            Header locationHeader = postMethod.getResponseHeader("location");
            String location = null;
            if (locationHeader != null) {
                location = locationHeader.getValue();
                log.info("The page was redirected to:" + location);
            } else {
                log.info("Location field value is null.");
            }
        }

        //? 
        byte[] responseBody = postMethod.getResponseBody();
        if (responseBody == null) {
            log.error("[HTTP response is null]:please check login or servlet");
            return "";
        }
        //?utf-8
        response = new String(responseBody, "UTF-8");
        //?
        log.info("[The Post Request's Response][" + url + "]" + response);

        // responseoutput
        File resfile = FileUtil.rewriteFile(file.getParentFile().getParent() + Constant.FILENAME_OUTPUT,
                file.getName().substring(0, file.getName().indexOf(".")) + ".response", response);

        // 
        vargen.processProps(resfile);
        //??
        if (this.itest_expect != null && this.itest_expect.trim().length() != 0) {
            Assert.assertTrue(
                    "response different with expect:[expect]:" + this.itest_expect + "[actual]:" + response,
                    response.contains(this.itest_expect));
        }
        //                  if(this.itest_expect_json!=null&&this.itest_expect_json.trim().length()!=0){
        //                     VerifyJsonTypeResponseImpl.verifyResponseWithJson(this.itest_expect_json,response);
        //
        //                  }

    } catch (HttpException e) {
        //?????
        log.error("Please check your provided http address!" + e.getMessage());

    } catch (IOException e) {
        //?
        log.error(e.getMessage());
    } catch (Exception e) {
        log.error("[HTTP REQUEST ERROR]:", e);
        //case fail
        throw new RuntimeException("HTTP REQUEST ERROR:" + e.getMessage());
    } finally {
        //
        postMethod.releaseConnection();
    }
    return response;
}

From source file:com.mengka.diamond.sdkapi.impl.DiamondSDKManagerImpl.java

public BatchContextResult<ConfigInfoEx> batchAddOrUpdate(String serverId, String groupName,
        Map<String, String> dataId2ContentMap) {
    // //from  w ww.ja v  a2 s .  co m
    BatchContextResult<ConfigInfoEx> response = new BatchContextResult<ConfigInfoEx>();

    // map?null
    if (dataId2ContentMap == null) {
        log.error("dataId2ContentMap cannot be null, serverId=" + serverId + " ,group=" + groupName);
        response.setSuccess(false);
        response.setStatusMsg("dataId2ContentMap cannot be null");
        return response;
    }

    // dataIdcontentmap????
    StringBuilder allDataIdAndContentBuilder = new StringBuilder();
    for (String dataId : dataId2ContentMap.keySet()) {
        String content = dataId2ContentMap.get(dataId);
        allDataIdAndContentBuilder.append(dataId + Constants.WORD_SEPARATOR + content)
                .append(Constants.LINE_SEPARATOR);
    }
    String allDataIdAndContent = allDataIdAndContentBuilder.toString();

    // 
    if (!login(serverId)) {
        response.setSuccess(false);
        response.setStatusMsg("login fail, serverId=" + serverId);
        return response;
    }

    // HTTP method
    PostMethod post = new PostMethod("/diamond-server/admin.do?method=batchAddOrUpdate");
    // 
    post.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, require_timeout);
    try {
        // ?
        NameValuePair dataId_value = new NameValuePair("allDataIdAndContent", allDataIdAndContent);
        NameValuePair group_value = new NameValuePair("group", groupName);

        post.setRequestBody(new NameValuePair[] { dataId_value, group_value });

        // http??
        int status = client.executeMethod(post);
        response.setStatusCode(status);
        String responseMsg = post.getResponseBodyAsString();
        response.setResponseMsg(responseMsg);

        if (status == HttpStatus.SC_OK) {
            String json = null;
            try {
                json = responseMsg;

                // ???json, ??BatchContextResult
                List<ConfigInfoEx> configInfoExList = new LinkedList<ConfigInfoEx>();
                Object resultObj = JSONUtils.deserializeObject(json, new TypeReference<List<ConfigInfoEx>>() {
                });
                if (!(resultObj instanceof List<?>)) {
                    throw new RuntimeException("batch write deserialize type error, not list, json=" + json);
                }
                List<ConfigInfoEx> resultList = (List<ConfigInfoEx>) resultObj;
                for (ConfigInfoEx configInfoEx : resultList) {
                    configInfoExList.add(configInfoEx);
                }
                response.getResult().addAll(configInfoExList);
                // ????, ???
                response.setStatusMsg("batch write success");
                log.info("batch write success,serverId=" + serverId + ",allDataIdAndContent="
                        + allDataIdAndContent + ",group=" + groupName + ",json=" + json);
            } catch (Exception e) {
                response.setSuccess(false);
                response.setStatusMsg("batch write deserialize error");
                log.error("batch write deserialize error, serverId=" + serverId + ",allDataIdAndContent="
                        + allDataIdAndContent + ",group=" + groupName + ",json=" + json, e);
            }
        } else if (status == HttpStatus.SC_REQUEST_TIMEOUT) {
            response.setSuccess(false);
            response.setStatusMsg("batch write timeout, socket timeout(ms):" + require_timeout);
            log.error("batch write timeout, socket timeout(ms):" + require_timeout + ", serverId=" + serverId
                    + ",allDataIdAndContent=" + allDataIdAndContent + ",group=" + groupName);
        } else {
            response.setSuccess(false);
            response.setStatusMsg("batch write fail, status:" + status);
            log.error("batch write fail, status:" + status + ", response:" + responseMsg + ",serverId="
                    + serverId + ",allDataIdAndContent=" + allDataIdAndContent + ",group=" + groupName);
        }
    } catch (HttpException e) {
        response.setSuccess(false);
        response.setStatusMsg("batch write http exception" + e.getMessage());
        log.error("batch write http exception, serverId=" + serverId + ",allDataIdAndContent="
                + allDataIdAndContent + ",group=" + groupName, e);
    } catch (IOException e) {
        response.setSuccess(false);
        response.setStatusMsg("batch write io exception" + e.getMessage());
        log.error("batch write io exception, serverId=" + serverId + ",allDataIdAndContent="
                + allDataIdAndContent + ",group=" + groupName, e);
    } finally {
        // ?
        post.releaseConnection();
    }

    return response;
}

From source file:com.taobao.diamond.sdkapi.impl.DiamondSDKManagerImpl.java

/**
 *  httpclient//from w  w  w. j  a v a2  s.  co m
 * 
 * @return  true:,false:
 */

private boolean login(String serverId) {
    // serverId 
    if (StringUtils.isEmpty(serverId) || StringUtils.isBlank(serverId))
        return false;
    DiamondSDKConf defaultConf = diamondSDKConfMaps.get(serverId);
    log.info("[login] serverId:" + serverId + "," + defaultConf);
    if (null == defaultConf)
        return false;
    RandomDiamondUtils util = new RandomDiamondUtils();
    // 
    util.init(defaultConf.getDiamondConfs());
    if (defaultConf.getDiamondConfs().size() == 0)
        return false;
    boolean flag = false;
    log.info("[randomSequence] : " + util.getSequenceToString());
    // diamondConf
    while (util.getRetry_times() < util.getMax_times()) {

        // diamondConf
        DiamondConf diamondConf = util.generatorOneDiamondConf();
        log.info("" + util.getRetry_times() + ":" + diamondConf);
        if (diamondConf == null)
            break;
        client.getHostConfiguration().setHost(diamondConf.getDiamondIp(),
                Integer.parseInt(diamondConf.getDiamondPort()), "http");
        PostMethod post = new PostMethod("/diamond-server/login.do?method=login");
        // 
        post.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, require_timeout);
        // 
        NameValuePair username_value = new NameValuePair("username", diamondConf.getDiamondUsername());
        NameValuePair password_value = new NameValuePair("password", diamondConf.getDiamondPassword());
        // 
        post.setRequestBody(new NameValuePair[] { username_value, password_value });
        log.info("diamondIp: " + diamondConf.getDiamondIp() + ",diamondPort: "
                + diamondConf.getDiamondPort() + ",diamondUsername: " + diamondConf.getDiamondUsername()
                + ",diamondPassword: " + diamondConf.getDiamondPassword() + "diamondServerUrl: ["
                + diamondConf.getDiamondConUrl() + "]");

        try {
            int state = client.executeMethod(post);
            log.info("" + state);
            // 200,true
            if (state == HttpStatus.SC_OK) {
                log.info("" + util.getRetry_times() + "");
                flag = true;
                break;
            }

        } catch (HttpException e) {
            log.error("HttpException", e);
        } catch (IOException e) {
            log.error("IOException", e);
        } finally {
            post.releaseConnection();
        }
    }
    if (flag == false) {
        log.error("logindiamondServerserverId=" + serverId);
    }
    return flag;
}