Java Code Examples for org.apache.commons.httpclient.methods.PostMethod#getResponseBodyAsString()

The following examples show how to use org.apache.commons.httpclient.methods.PostMethod#getResponseBodyAsString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RestClient.java    From maven-framework-project with MIT License 7 votes vote down vote up
public Book getBook(String bookName) throws Exception {

        String output = null;
        try{
            String url = "http://localhost:8080/bookservice/getbook/";

            url = url + URLEncoder.encode(bookName, "UTF-8");

            HttpClient client = new HttpClient();
            PostMethod mPost = new PostMethod(url);
            client.executeMethod( mPost );
            Header mtHeader = new Header();
            mtHeader.setName("content-type");
            mtHeader.setValue("application/x-www-form-urlencoded");
            mtHeader.setName("accept");
            mtHeader.setValue("application/xml");
            mPost.addRequestHeader(mtHeader);
            client.executeMethod(mPost);
            output = mPost.getResponseBodyAsString( );
            mPost.releaseConnection( );
            System.out.println("out : " + output);
        }catch(Exception e){
            throw new Exception("Exception in retriving group page info : " + e);
        }
        return null;
    }
 
Example 2
Source File: RestClient.java    From maven-framework-project with MIT License 6 votes vote down vote up
public void addBook(String bookName, String author) throws Exception {

        String output = null;
        try{
            String url = "http://localhost:8080/bookservice/addbook";
            HttpClient client = new HttpClient();
            PostMethod mPost = new PostMethod(url);
            mPost.addParameter("name", "Naked Sun");
            mPost.addParameter("author", "Issac Asimov");
            Header mtHeader = new Header();
            mtHeader.setName("content-type");
            mtHeader.setValue("application/x-www-form-urlencoded");
            mtHeader.setName("accept");
            mtHeader.setValue("application/xml");
            //mtHeader.setValue("application/json");
            mPost.addRequestHeader(mtHeader);
            client.executeMethod(mPost);
            output = mPost.getResponseBodyAsString( );
            mPost.releaseConnection( );
            System.out.println("output : " + output);
        }catch(Exception e){
            throw new Exception("Exception in adding bucket : " + e);
        }

    }
 
Example 3
Source File: UsernamePasswordAuthentication.java    From JavaChatterRESTApi with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * <p>Authenticate using a username and password. This is discouraged by the oauth flow,
 * but it allows for transparent (and non human-intervention) authentication).</p>
 * 
 * @return The response retrieved from the REST API (usually an XML string with all the tokens)
 * @throws IOException
 * @throws UnauthenticatedSessionException
 * @throws AuthenticationException
 */
public ChatterAuthToken authenticate() throws IOException, UnauthenticatedSessionException, AuthenticationException {
    String clientId = URLEncoder.encode(chatterData.getClientKey(), "UTF-8");
    String clientSecret = chatterData.getClientSecret();
    String username = chatterData.getUsername();
    String password = chatterData.getPassword();

    String authenticationUrl = "TEST".equalsIgnoreCase(chatterData.getEnvironment()) ? TEST_AUTHENTICATION_URL : PRODUCTION_AUTHENTICATION_URL;
    PostMethod post = new PostMethod(authenticationUrl);

    NameValuePair[] data = { new NameValuePair("grant_type", "password"), new NameValuePair("client_id", clientId),
        new NameValuePair("client_secret", clientSecret), new NameValuePair("username", username),
        new NameValuePair("password", password) };

    post.setRequestBody(data);

    int statusCode = getHttpClient().executeMethod(post);
    if (statusCode == HttpStatus.SC_OK) {
        return processResponse(post.getResponseBodyAsString());
    }

    throw new UnauthenticatedSessionException(statusCode + " " + post.getResponseBodyAsString());
}
 
Example 4
Source File: GDataAuthStrategy.java    From rome with Apache License 2.0 6 votes vote down vote up
private void init() throws ProponoException {
    try {
        final HttpClient httpClient = new HttpClient();
        final PostMethod method = new PostMethod("https://www.google.com/accounts/ClientLogin");
        final NameValuePair[] data = { new NameValuePair("Email", email), new NameValuePair("Passwd", password),
                new NameValuePair("accountType", "GOOGLE"), new NameValuePair("service", service),
                new NameValuePair("source", "ROME Propono Atompub Client") };
        method.setRequestBody(data);
        httpClient.executeMethod(method);

        final String responseBody = method.getResponseBodyAsString();
        final int authIndex = responseBody.indexOf("Auth=");

        authToken = "GoogleLogin auth=" + responseBody.trim().substring(authIndex + 5);

    } catch (final Throwable t) {
        t.printStackTrace();
        throw new ProponoException("ERROR obtaining Google authentication string", t);
    }
}
 
Example 5
Source File: ClientSecretAuthentication.java    From JavaChatterRESTApi with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * <p>Authenticate using a client Secret. This is usually gotten by either asking the user,
 * or by using a callback. This allows for transparent (and non human-intervention) authentication.</p>
 * 
 * @return The response retrieved from the REST API (usually an XML string with all the tokens)
 * @throws IOException
 * @throws UnauthenticatedSessionException
 * @throws AuthenticationException
 */
public ChatterAuthToken authenticate() throws IOException, UnauthenticatedSessionException, AuthenticationException {
    String clientId = chatterData.getClientKey();
    String clientSecret = chatterData.getClientSecret();
    String clientRedirect = chatterData.getClientCallback();
    String clientCode = this.clientCode;

    if (null == clientCode && null != chatterData.getClientCode()) {
        clientCode = chatterData.getClientCode();
    }

    String authenticationUrl = "TEST".equalsIgnoreCase(chatterData.getEnvironment()) ? TEST_AUTHENTICATION_URL : PRODUCTION_AUTHENTICATION_URL;
    PostMethod post = new PostMethod(authenticationUrl);

    NameValuePair[] data = { new NameValuePair("grant_type", "authorization_code"),
        new NameValuePair("client_id", clientId), new NameValuePair("client_secret", clientSecret),
        new NameValuePair("redirect_uri", clientRedirect), new NameValuePair("code", clientCode) };
    
    post.setRequestBody(data);
    int statusCode = getHttpClient().executeMethod(post);
    if (statusCode == HttpStatus.SC_OK) {
        return processResponse(post.getResponseBodyAsString());
    }

    throw new UnauthenticatedSessionException(statusCode + " " + post.getResponseBodyAsString());
}
 
Example 6
Source File: HelpTest.java    From markdown-image-kit with MIT License 6 votes vote down vote up
private HttpClient help(String where) throws Exception {
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod("http://127.0.0.1:8080/rest/help/" + where);
    client.getParams().setContentCharset("UTF-8");
    client.executeMethod(method);
    String response;
    try {
        response = method.getResponseBodyAsString(1000);
    } finally {
        method.releaseConnection();
    }
    if (response == null) {
        throw new NullPointerException();
    }
    return client;
}
 
Example 7
Source File: HttpUtil.java    From OfficeAutomatic-System with Apache License 2.0 6 votes vote down vote up
public static String sendPost(String urlParam) throws HttpException, IOException {
    // 创建httpClient实例对象
    HttpClient httpClient = new HttpClient();
    // 设置httpClient连接主机服务器超时时间:15000毫秒
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
    // 创建post请求方法实例对象
    PostMethod postMethod = new PostMethod(urlParam);
    // 设置post请求超时时间
    postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
    postMethod.addRequestHeader("Content-Type", "application/json");

    httpClient.executeMethod(postMethod);

    String result = postMethod.getResponseBodyAsString();
    postMethod.releaseConnection();
    return result;
}
 
Example 8
Source File: ESBJAVA4846HttpProtocolVersionTestCase.java    From product-ei with Apache License 2.0 6 votes vote down vote up
@Test(groups = "wso2.esb", description = "Sending HTTP1.1 message")
public void sendingHTTP11Message() throws Exception {
    PostMethod post = new PostMethod(getProxyServiceURLHttp("StockQuoteProxyTestHTTPVersion"));
    RequestEntity entity = new StringRequestEntity(getPayload(), "text/xml", "UTF-8");
    post.setRequestEntity(entity);
    post.setRequestHeader("SOAPAction", "urn:getQuote");
    HttpMethodParams params = new HttpMethodParams();
    params.setVersion(HttpVersion.HTTP_1_1);
    post.setParams(params);
    HttpClient httpClient = new HttpClient();
    String httpVersion = "";

    try {
        httpClient.executeMethod(post);
        post.getResponseBodyAsString();
        httpVersion = post.getStatusLine().getHttpVersion();
    } finally {
        post.releaseConnection();
    }
    Assert.assertEquals(httpVersion, HttpVersion.HTTP_1_1.toString(), "Http version mismatched");
}
 
Example 9
Source File: ESBJAVA4846HttpProtocolVersionTestCase.java    From product-ei with Apache License 2.0 6 votes vote down vote up
@Test(groups = "wso2.esb", description = "Sending HTTP1.0 message")
public void sendingHTTP10Message() throws Exception {
    PostMethod post = new PostMethod(getProxyServiceURLHttp("StockQuoteProxyTestHTTPVersion"));
    RequestEntity entity = new StringRequestEntity(getPayload(), "text/xml", "UTF-8");
    post.setRequestEntity(entity);
    post.setRequestHeader("SOAPAction", "urn:getQuote");
    HttpMethodParams params = new HttpMethodParams();
    params.setVersion(HttpVersion.HTTP_1_0);
    post.setParams(params);
    HttpClient httpClient = new HttpClient();
    String httpVersion = "";

    try {
        httpClient.executeMethod(post);
        post.getResponseBodyAsString();
        httpVersion = post.getStatusLine().getHttpVersion();
    } finally {
        post.releaseConnection();
    }
    Assert.assertEquals(httpVersion, HttpVersion.HTTP_1_0.toString(), "Http version mismatched");

}
 
Example 10
Source File: SecurityGroupHttpClient.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public HashMap<String, Pair<Long, Long>> sync(String vmName, Long vmId, String agentIp) {
    HashMap<String, Pair<Long, Long>> states = new HashMap<String, Pair<Long, Long>>();
    PostMethod post = new PostMethod(String.format("http://%s:%s/", agentIp, getPort()));
    try {
        post.addRequestHeader("command", "sync");
        if (httpClient.executeMethod(post) != 200) {
            logger.debug(String.format("echoing baremetal security group agent on %s got error: %s", agentIp, post.getResponseBodyAsString()));
        } else {
            String res = post.getResponseBodyAsString();
            // res = ';'.join([vmName, vmId, seqno])
            String[] rulelogs = res.split(",");
            if (rulelogs.length != 6) {
                logger.debug(String.format("host[%s] returns invalid security group sync document[%s], reset rules", agentIp, res));
                states.put(vmName, new Pair<Long, Long>(vmId, -1L));
                return states;
            }
            Pair<Long, Long> p = new Pair<Long, Long>(Long.valueOf(rulelogs[1]), Long.valueOf(rulelogs[5]));
            states.put(rulelogs[0], p);
            return states;
        }
    } catch (SocketTimeoutException se) {
        logger.warn(String.format("unable to sync security group rules on host[%s], %s", agentIp, se.getMessage()));
    } catch (Exception e) {
        logger.warn(String.format("unable to sync security group rules on host[%s]", agentIp), e);
    } finally {
        if (post != null) {
            post.releaseConnection();
        }
    }
    return states;
}
 
Example 11
Source File: MatrixUtil.java    From boubei-tss with Apache License 2.0 5 votes vote down vote up
public static void exePostMethod(PostMethod postMethod) {
	HttpClient httpClient = new HttpClient();
	
	int statusCode = 0;
	String rtMsg = null;
	try {
        statusCode = httpClient.executeMethod(postMethod);
        rtMsg = postMethod.getResponseBodyAsString();
	} 
	catch(Exception e) {
		rtMsg = e.getMessage();
	} 
	log.debug("remote record result: " + statusCode + ", " + rtMsg);
}
 
Example 12
Source File: HttpUtils.java    From Java-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * 处理Post请求
 * @param url
 * @param params post请求参数
 * @param jsonString post传递json数据
 * @return
 * @throws HttpException
 * @throws IOException
 */
public static JSONObject doPost(String url,Map<String,String> headers,Map<String,String> params,String jsonString) {
	
	HttpClient client = new HttpClient();
	//post请求
	PostMethod postMethod = new PostMethod(url);
	
	//设置header
	setHeaders(postMethod,headers);
	
	//设置post请求参数
	setParams(postMethod,params);
	
	//设置post传递的json数据
	if(jsonString!=null&&!"".equals(jsonString)){
		postMethod.setRequestEntity(new ByteArrayRequestEntity(jsonString.getBytes()));
	}
	
	String responseStr = "";
	
	try {
		client.executeMethod(postMethod);
		responseStr = postMethod.getResponseBodyAsString();
	} catch (Exception e) {
		log.error(e);
		e.printStackTrace();
		responseStr="{status:0}";
	} 
	
	return JSONObject.parseObject(responseStr);
	
}
 
Example 13
Source File: CSP.java    From scim2-compliance-test-suite with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
public String getAccessToken() {
    if (this.oAuth2AccessToken != null) {
        return this.oAuth2AccessToken;
    }

    try {
        HttpClient client = new HttpClient();
        client.getParams().setAuthenticationPreemptive(true);
        Credentials defaultcreds = new UsernamePasswordCredentials(this.getUsername(), this.getPassword());
        client.getState().setCredentials(AuthScope.ANY, defaultcreds);

        PostMethod method = new PostMethod(this.getOAuthAuthorizationServer());
        method.setRequestBody("grant_type=client_credentials");
        int responseCode = client.executeMethod(method);
        if (responseCode != 200) {

            throw new RuntimeException("Failed to fetch access token form authorization server, " + this.getOAuthAuthorizationServer()
                    + ", got response code " + responseCode);
        }
        String responseBody = method.getResponseBodyAsString();
        JSONObject accessResponse = new JSONObject(responseBody);
        accessResponse.getString("access_token");
        return (this.oAuth2AccessToken = accessResponse.getString("access_token"));
    } catch (Exception e) {
        throw new RuntimeException("Failed to read response from authorizationServer at " + this.getOAuthAuthorizationServer(), e);
    }
}
 
Example 14
Source File: CSP.java    From scim2-compliance-test-suite with Apache License 2.0 5 votes vote down vote up
public String getAccessTokenUserPass() {
    if (!StringUtils.isEmpty(this.oAuth2AccessToken)) {
        return this.oAuth2AccessToken;
    }

    if (StringUtils.isEmpty(this.username) || StringUtils.isEmpty(this.password) && StringUtils.isEmpty(this.oAuth2AuthorizationServer)
            || StringUtils.isEmpty(this.oAuth2ClientId) || StringUtils.isEmpty(this.oAuth2ClientSecret)) {
        return "";
    }

    try {
        HttpClient client = new HttpClient();
        client.getParams().setAuthenticationPreemptive(true);

        // post development
        PostMethod method = new PostMethod(this.getOAuthAuthorizationServer());
        method.setRequestHeader(new Header("Content-type", "application/x-www-form-urlencoded"));

        method.addRequestHeader("Authorization", "Basic " + Base64.encodeBase64String((username + ":" + password).getBytes()));
        NameValuePair[] body = new NameValuePair[] { new NameValuePair("username", username), new NameValuePair("password", password),
                new NameValuePair("client_id", oAuth2ClientId), new NameValuePair("client_secret", oAuth2ClientSecret),
                new NameValuePair("grant_type", oAuth2GrantType) };
        method.setRequestBody(body);
        int responseCode = client.executeMethod(method);

        String responseBody = method.getResponseBodyAsString();
        if (responseCode != 200) {
            throw new RuntimeException("Failed to fetch access token form authorization server, " + this.getOAuthAuthorizationServer()
                    + ", got response code " + responseCode);
        }

        JSONObject accessResponse = new JSONObject(responseBody);
        accessResponse.getString("access_token");
        return (this.oAuth2AccessToken = accessResponse.getString("access_token"));
    } catch (Exception e) {
        throw new RuntimeException("Failed to read response from authorizationServer at " + this.getOAuthAuthorizationServer(), e);
    }
}
 
Example 15
Source File: UcsHttpClient.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public String call(String xml) {
    PostMethod post = new PostMethod(url);
    post.setRequestEntity(new StringRequestEntity(xml));
    post.setRequestHeader("Content-type", "text/xml");
    //post.setFollowRedirects(true);
    try {
        int result = client.executeMethod(post);
        if (result == 302) {
            // Handle HTTPS redirect
            // Ideal way might be to configure from add manager API
            // for using either HTTP / HTTPS
            // Allow only one level of redirect
            String redirectLocation;
            Header locationHeader = post.getResponseHeader("location");
            if (locationHeader != null) {
                redirectLocation = locationHeader.getValue();
            } else {
                throw new CloudRuntimeException("Call failed: Bad redirect from UCS Manager");
            }
            post.setURI(new URI(redirectLocation));
            result = client.executeMethod(post);
        }
        // Check for errors
        if (result != 200) {
            throw new CloudRuntimeException("Call failed: " + post.getResponseBodyAsString());
        }
        String res = post.getResponseBodyAsString();
        if (res.contains("errorCode")) {
            String err = String.format("ucs call failed:\nsubmitted doc:%s\nresponse:%s\n", xml, res);
            throw new CloudRuntimeException(err);
        }
        return res;
    } catch (Exception e) {
        throw new CloudRuntimeException(e.getMessage(), e);
    } finally {
        post.releaseConnection();
    }
}
 
Example 16
Source File: AuthUtil.java    From roncoo-pay with Apache License 2.0 5 votes vote down vote up
/**
 * post请求
 *
 * @param paramMap   请求参数
 * @param requestUrl 请求地址
 * @return
 */
private static Map<String, Object> request(SortedMap<String, String> paramMap, String requestUrl) {
    logger.info("鉴权请求地址:[{}],请求参数:[{}]", requestUrl, paramMap);
    HttpClient httpClient = new HttpClient();
    HttpConnectionManagerParams managerParams = httpClient.getHttpConnectionManager().getParams();
    // 设置连接超时时间(单位毫秒)
    managerParams.setConnectionTimeout(9000);
    // 设置读数据超时时间(单位毫秒)
    managerParams.setSoTimeout(12000);
    PostMethod postMethod = new PostMethod(requestUrl);
    postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
    NameValuePair[] pairs = new NameValuePair[paramMap.size()];
    int i = 0;
    for (Map.Entry<String, String> entry : paramMap.entrySet()) {
        pairs[i++] = new NameValuePair(entry.getKey(), entry.getValue());
    }
    postMethod.setRequestBody(pairs);
    try {
        Integer code = httpClient.executeMethod(postMethod);
        if (code.compareTo(200) == 0) {
            String result = postMethod.getResponseBodyAsString();
            logger.info("鉴权请求成功,同步返回数据:{}", result);
            return JSON.parseObject(result);
        } else {
            logger.error("鉴权请求失败,返回状态码:[{}]", code);
        }
    } catch (IOException e) {
        logger.info("鉴权请求异常:{}", e);
        return null;
    }
    return null;
}
 
Example 17
Source File: ESBJAVA_4118_SOAPHeaderHandlingTest.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
@Test(groups = "wso2.esb", description = "Test whether the callout mediator successfully handle SOAP messages "
        + "Having SOAP header")
public void testSOAPHeaderHandling() throws Exception {
    String endpoint = "http://localhost:8480/services/TestCalloutSoapHeader";
    String soapRequest =
            TestConfigurationProvider.getResourceLocation() + "artifacts" + File.separator + "ESB" + File.separator
                    + "mediatorconfig" + File.separator + "callout" + File.separator + "SOAPRequestWithHeader.xml";
    File input = new File(soapRequest);
    PostMethod post = new PostMethod(endpoint);
    RequestEntity entity = new FileRequestEntity(input, "text/xml");
    post.setRequestEntity(entity);
    post.setRequestHeader("SOAPAction", "getQuote");
    HttpClient httpClient = new HttpClient();
    boolean errorLog = false;

    try {
        int result = httpClient.executeMethod(post);
        String responseBody = post.getResponseBodyAsString();
        log.info("Response Status: " + result);
        log.info("Response Body: " + responseBody);

        errorLog = carbonLogReader.checkForLog("Unable to convert to SoapHeader Block", DEFAULT_TIMEOUT);
        carbonLogReader.stop();
    } finally {
        post.releaseConnection();
    }
    assertFalse(errorLog, "Mediator Hasn't invoked successfully.");
}
 
Example 18
Source File: HuaXinSMSProvider.java    From ZTuoExchange_framework with MIT License 4 votes vote down vote up
@Override
public MessageResult sendInternationalMessage(String content, String phone) throws IOException, DocumentException {
    content=String.format("[%s]Verification Code:%s.If you do not send it, please ignore this message.", sign,content);
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(internationalGateway);
    String result = encodeHexStr(8, content);
    client.getParams().setContentCharset("UTF-8");
    method.setRequestHeader("ContentType",
            "application/x-www-form-urlencoded;charset=UTF-8");
    NameValuePair[] data = {new NameValuePair("action", "send"),
            new NameValuePair("userid", ""),
            new NameValuePair("account", internationalUsername),
            new NameValuePair("password", internationalPassword),
            new NameValuePair("mobile", phone),
            //发英文 用  0    其他中日韩 用  8
            new NameValuePair("code", "8"),
            new NameValuePair("content", result),
            new NameValuePair("sendTime", ""),
            new NameValuePair("extno", ""),};
    method.setRequestBody(data);
    client.executeMethod(method);
    String response = method.getResponseBodyAsString();
    Document doc = DocumentHelper.parseText(response);
    // 获取根节点
    Element rootElt = doc.getRootElement();
    // 获取根节点下的子节点的值
    String returnstatus = rootElt.elementText("returnstatus").trim();
    String message = rootElt.elementText("message").trim();
    String remainpoint = rootElt.elementText("balance").trim();
    String taskID = rootElt.elementText("taskID").trim();
    String successCounts = rootElt.elementText("successCounts").trim();

    System.out.println(response);
    System.out.println("返回状态为:" + returnstatus);
    System.out.println("返回信息提示:" + message);
    System.out.println("返回余额:" + remainpoint);
    System.out.println("返回任务批次:" + taskID);
    System.out.println("返回成功条数:" + successCounts);

    MessageResult messageResult = MessageResult.success();
    if (!"Success".equals(returnstatus)) {
        messageResult.setCode(500);
    }
    messageResult.setMessage(message);
    return messageResult;
}
 
Example 19
Source File: InterpreterRestApiTest.java    From zeppelin with Apache License 2.0 4 votes vote down vote up
@Test
public void testSettingsCRUD() throws IOException {
  // when: call create setting API
  String rawRequest = "{\"name\":\"md3\",\"group\":\"md\"," +
          "\"properties\":{\"propname\": {\"value\": \"propvalue\", \"name\": \"propname\", " +
          "\"type\": \"textarea\"}}," +
          "\"interpreterGroup\":[{\"class\":\"org.apache.zeppelin.markdown.Markdown\"," +
          "\"name\":\"md\"}],\"dependencies\":[]," +
          "\"option\": { \"remote\": true, \"session\": false }}";
  JsonObject jsonRequest = gson.fromJson(rawRequest, JsonElement.class).getAsJsonObject();
  PostMethod post = httpPost("/interpreter/setting/", jsonRequest.toString());
  String postResponse = post.getResponseBodyAsString();
  LOG.info("testSettingCRUD create response\n" + post.getResponseBodyAsString());
  InterpreterSetting created = convertResponseToInterpreterSetting(postResponse);
  String newSettingId = created.getId();
  // then : call create setting API
  assertThat("test create method:", post, isAllowed());
  post.releaseConnection();

  // when: call read setting API
  GetMethod get = httpGet("/interpreter/setting/" + newSettingId);
  String getResponse = get.getResponseBodyAsString();
  LOG.info("testSettingCRUD get response\n" + getResponse);
  InterpreterSetting previouslyCreated = convertResponseToInterpreterSetting(getResponse);
  // then : read Setting API
  assertThat("Test get method:", get, isAllowed());
  assertEquals(newSettingId, previouslyCreated.getId());
  get.releaseConnection();

  // when: call update setting API
  JsonObject jsonObject = new JsonObject();
  jsonObject.addProperty("name", "propname2");
  jsonObject.addProperty("value", "this is new prop");
  jsonObject.addProperty("type", "textarea");
  jsonRequest.getAsJsonObject("properties").add("propname2", jsonObject);
  PutMethod put = httpPut("/interpreter/setting/" + newSettingId, jsonRequest.toString());
  LOG.info("testSettingCRUD update response\n" + put.getResponseBodyAsString());
  // then: call update setting API
  assertThat("test update method:", put, isAllowed());
  put.releaseConnection();

  // when: call delete setting API
  DeleteMethod delete = httpDelete("/interpreter/setting/" + newSettingId);
  LOG.info("testSettingCRUD delete response\n" + delete.getResponseBodyAsString());
  // then: call delete setting API
  assertThat("Test delete method:", delete, isAllowed());
  delete.releaseConnection();
}
 
Example 20
Source File: HttpClientUtil.java    From AndroidRobot with Apache License 2.0 4 votes vote down vote up
/**
 * @param url
 * @param queryString 类似a=b&c=d 形式的参数
 * 
 * @param obj   发送到服务器的对象。
 *     
 * @return 服务器返回到客户端的对象。
 * @throws IOException
 */
public static String httpObjRequest(String url, Object obj, String queryString ) throws IOException
{
	String response = null;
	HttpClient client = new HttpClient();
    
    PostMethod post = new PostMethod(url);
    
    post.setQueryString(queryString);

    post.setRequestHeader("Content-Type", "application/octet-stream");

    java.io.ByteArrayOutputStream bOut = new java.io.ByteArrayOutputStream(1024);
    java.io.ByteArrayInputStream bInput = null;
    java.io.ObjectOutputStream out = null;
    
    try
    {
        out = new java.io.ObjectOutputStream(bOut);

        out.writeObject(obj);

        out.flush();
        out.close();

        out = null;

        bInput = new java.io.ByteArrayInputStream(bOut.toByteArray());

        RequestEntity re = new InputStreamRequestEntity(bInput);
        post.setRequestEntity(re);

        client.executeMethod(post);
        response = post.getResponseBodyAsString();
        System.out.println("URI:" + post.getURI());
    }
    catch (IOException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    finally
    {
        if (out != null)
        {
            out.close();
            out = null;

        }

        if (bInput != null)
        {
            bInput.close();
            bInput = null;

        }
        //释放连接
        post.releaseConnection();
    }

    return response;

}