下面列出了怎么用org.apache.commons.httpclient.methods.PostMethod的API类实例代码及写法,或者点击链接到github查看源代码。
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;
}
/**
* <p>This creates a HttpMethod with the message as its payload and image attachment. The message should be a properly formatted JSON
* String (No validation is done on this).</p>
*
* <p>The message can be easily created using the {@link #getJsonPayload(Message)} method.</p>
*
* @param uri The full URI which we will post to
* @param message A properly formatted JSON message. UTF-8 is expected
* @param image A complete instance of ImageAttachment object
* @throws IOException
*/
public HttpMethod getJsonPostForMultipartRequestEntity(String uri, String message, ImageAttachment image) throws IOException {
PostMethod post = new PostMethod(uri);
StringPart bodyPart = new StringPart("json", message);
bodyPart.setContentType("application/json");
FilePart filePart= new FilePart("feedItemFileUpload", image.retrieveObjectFile());
filePart.setContentType(image.retrieveContentType());
Part[] parts = {
bodyPart,
filePart,
};
post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
return post;
}
/**
* Test that blob upload requests are intercepted by the blob upload filter.
*
* @throws Exception
*/
public void testBlobUpload() throws Exception {
String postData = "--==boundary\r\n" + "Content-Type: message/external-body; "
+ "charset=ISO-8859-1; blob-key=\"blobkey:blob-0\"\r\n" + "Content-Disposition: form-data; "
+ "name=upload-0; filename=\"file-0.jpg\"\r\n" + "\r\n" + "Content-Type: image/jpeg\r\n"
+ "Content-Length: 1024\r\n" + "X-AppEngine-Upload-Creation: 2009-04-30 17:12:51.675929\r\n"
+ "Content-Disposition: form-data; " + "name=upload-0; filename=\"file-0.jpg\"\r\n" + "\r\n"
+ "\r\n" + "--==boundary\r\n" + "Content-Type: text/plain; charset=ISO-8859-1\r\n"
+ "Content-Disposition: form-data; name=text1\r\n" + "Content-Length: 10\r\n" + "\r\n"
+ "Testing.\r\n" + "\r\n" + "\r\n" + "--==boundary--";
HttpClient httpClient = new HttpClient();
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
PostMethod blobPost = new PostMethod(createUrl("/upload-blob").toString());
blobPost.addRequestHeader("Content-Type", "multipart/form-data; boundary=\"==boundary\"");
blobPost.addRequestHeader("X-AppEngine-BlobUpload", "true");
blobPost.setRequestBody(postData);
int httpCode = httpClient.executeMethod(blobPost);
assertEquals(302, httpCode);
Header redirUrl = blobPost.getResponseHeader("Location");
assertEquals("http://" + getServerHost() + "/serve-blob?key=blobkey:blob-0",
redirUrl.getValue());
}
private String httpClient(String proxyLocation, String xml) {
try {
HttpClient httpclient = new HttpClient();
PostMethod post = new PostMethod(proxyLocation);
post.setRequestEntity(new StringRequestEntity(xml));
post.setRequestHeader("Content-type", "text/xml; charset=ISO-8859-1");
post.setRequestHeader("SOAPAction", "urn:mediate");
httpclient.executeMethod(post);
InputStream in = post.getResponseBodyAsStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
StringBuffer buffer = new StringBuffer();
while ((line = reader.readLine()) != null) {
buffer.append(line);
buffer.append("\n");
}
reader.close();
return buffer.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Test(groups = "wso2.esb", description = "Testing functionality of FORCE_SC_ACCEPTED " + "- Enabled False")
public void testFORCE_SC_ACCEPTEDPropertyEnabledFalseScenario() throws Exception {
int responseStatus = 0;
String strXMLFilename =
FrameworkPathUtil.getSystemResourceLocation() + "artifacts" + File.separator + "ESB" + File.separator
+ "mediatorconfig" + File.separator + "property" + File.separator + "GetQuoteRequest.xml";
File input = new File(strXMLFilename);
PostMethod post = new PostMethod(getProxyServiceURLHttp("FORCE_SC_ACCEPTED_FalseTestProxy"));
RequestEntity entity = new FileRequestEntity(input, "text/xml");
post.setRequestEntity(entity);
post.setRequestHeader("SOAPAction", "getQuote");
HttpClient httpclient = new HttpClient();
try {
responseStatus = httpclient.executeMethod(post);
} finally {
post.releaseConnection();
}
assertEquals(responseStatus, 200, "Response status should be 200");
}
@Test(groups = "wso2.esb", description = "Testing functionality of FORCE_SC_ACCEPTED " + "Enabled True - "
+ "Client should receive 202 message", dependsOnMethods = "testFORCE_SC_ACCEPTEDPropertyEnabledFalseScenario")
public void testWithFORCE_SC_ACCEPTEDPropertyEnabledTrueScenario() throws Exception {
int responseStatus = 0;
String strXMLFilename =
FrameworkPathUtil.getSystemResourceLocation() + "artifacts" + File.separator + "ESB" + File.separator
+ "mediatorconfig" + File.separator + "property" + File.separator + "PlaceOrder.xml";
File input = new File(strXMLFilename);
PostMethod post = new PostMethod(getProxyServiceURLHttp("FORCE_SC_ACCEPTED_TrueTestProxy"));
RequestEntity entity = new FileRequestEntity(input, "text/xml");
post.setRequestEntity(entity);
post.setRequestHeader("SOAPAction", "placeOrder");
HttpClient httpclient = new HttpClient();
try {
responseStatus = httpclient.executeMethod(post);
} finally {
post.releaseConnection();
}
assertEquals(responseStatus, 202, "Response status should be 202");
}
private String httpClient(String proxyLocation, String xml) {
try {
HttpClient httpclient = new HttpClient();
PostMethod post = new PostMethod(proxyLocation);
post.setRequestEntity(new StringRequestEntity(xml));
post.setRequestHeader("Content-type", "text/xml; charset=ISO-8859-1");
post.setRequestHeader("SOAPAction", "urn:mediate");
httpclient.executeMethod(post);
InputStream in = post.getResponseBodyAsStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
StringBuffer buffer = new StringBuffer();
while ((line = reader.readLine()) != null) {
buffer.append(line);
buffer.append("\n");
}
reader.close();
return buffer.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
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;
}
@Test(groups = "wso2.esb", description = "Getting HTTP status code number ")
public void testHttpResponseCode() throws Exception {
int responseStatus = 0;
String strXMLFilename = FrameworkPathUtil.getSystemResourceLocation() + "artifacts"
+ File.separator + "ESB" + File.separator + "mediatorconfig" +
File.separator + "property" + File.separator + "GetQuoteRequest.xml";
File input = new File(strXMLFilename);
PostMethod post = new PostMethod(getProxyServiceURLHttp("HTTP_SCTestProxy"));
RequestEntity entity = new FileRequestEntity(input, "text/xml");
post.setRequestEntity(entity);
post.setRequestHeader("SOAPAction", "getQuote");
HttpClient httpclient = new HttpClient();
try {
responseStatus = httpclient.executeMethod(post);
} finally {
post.releaseConnection();
}
assertEquals(responseStatus, 404, "Response status should be 404");
}
protected HttpMethod createMethod(final String type, final String uri, final int port) throws BigSwitchBcfApiException {
String url;
try {
url = new URL(S_PROTOCOL, host, port, uri).toString();
} catch (MalformedURLException e) {
S_LOGGER.error("Unable to build Big Switch API URL", e);
throw new BigSwitchBcfApiException("Unable to build Big Switch API URL", e);
}
if ("post".equalsIgnoreCase(type)) {
return new PostMethod(url);
} else if ("get".equalsIgnoreCase(type)) {
return new GetMethod(url);
} else if ("delete".equalsIgnoreCase(type)) {
return new DeleteMethod(url);
} else if ("put".equalsIgnoreCase(type)) {
return new PutMethod(url);
} else {
throw new BigSwitchBcfApiException("Requesting unknown method type");
}
}
@Test(expected = UnauthenticatedSessionException.class)
public void testBadResponseCode() throws HttpException, IOException, UnauthenticatedSessionException,
AuthenticationException {
IChatterData data = getMockedChatterData();
RefreshTokenAuthentication auth = new RefreshTokenAuthentication(data);
HttpClient mockHttpClient = mock(HttpClient.class);
when(mockHttpClient.executeMethod(any(PostMethod.class))).thenAnswer(
new ExecuteMethodAnswer("400 Bad Request", HttpStatus.SC_BAD_REQUEST));
auth.setHttpClient(mockHttpClient);
auth.authenticate();
fail();
}
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);
}
}
public static void callAPI(String url, String user, String uToken) throws HttpException, IOException {
if(url.indexOf("?") < 0) {
url += "?uName=" +user+ "&uToken=" + uToken;
}
else {
url += "&uName=" +user+ "&uToken=" + uToken;
}
PostMethod postMethod = new PostMethod(url);
postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
// 最后生成一个HttpClient对象,并发出postMethod请求
HttpClient httpClient = new HttpClient();
int statusCode = httpClient.executeMethod(postMethod);
if(statusCode == 200) {
System.out.print("返回结果: ");
String soapResponseData = postMethod.getResponseBodyAsString();
System.out.println(soapResponseData);
}
else {
System.out.println("调用失败!错误码:" + statusCode);
}
}
protected static HttpMethodBase buildHttpClientMethod(String url, String method)
{
if ("GET".equals(method))
{
return new GetMethod(url);
}
if ("POST".equals(method))
{
return new PostMethod(url);
}
if ("PUT".equals(method))
{
return new PutMethod(url);
}
if ("DELETE".equals(method))
{
return new DeleteMethod(url);
}
if (TestingMethod.METHOD_NAME.equals(method))
{
return new TestingMethod(url);
}
throw new UnsupportedOperationException("Method '"+method+"' not supported");
}
/**
* Test create target.
*
* @throws Exception
*/
public void testSuccessfulVerifyTargetOverHttp() throws Exception
{
//Stub HttpClient so that executeMethod returns a 200 response
when(mockedHttpClient.executeMethod(any(HostConfiguration.class), any(HttpMethod.class),
any(HttpState.class))).thenReturn(200);
//Call verifyTarget
transmitter.verifyTarget(target);
ArgumentCaptor<HostConfiguration> hostConfig = ArgumentCaptor.forClass(HostConfiguration.class);
ArgumentCaptor<HttpMethod> httpMethod = ArgumentCaptor.forClass(HttpMethod.class);
ArgumentCaptor<HttpState> httpState = ArgumentCaptor.forClass(HttpState.class);
verify(mockedHttpClient).executeMethod(hostConfig.capture(), httpMethod.capture(), httpState.capture());
assertTrue("post method", httpMethod.getValue() instanceof PostMethod);
assertEquals("host name", TARGET_HOST, hostConfig.getValue().getHost());
assertEquals("port", HTTP_PORT, hostConfig.getValue().getPort());
assertEquals("protocol", HTTP_PROTOCOL.toLowerCase(),
hostConfig.getValue().getProtocol().getScheme().toLowerCase());
assertEquals("path", TRANSFER_SERVICE_PATH + "/test", httpMethod.getValue().getPath());
}
@Test
public void testVisualizationPackageOrder() throws IOException {
GetMethod get1 = httpGet("/helium/order/visualization");
assertThat(get1, isAllowed());
Map<String, Object> resp1 = gson.fromJson(get1.getResponseBodyAsString(),
new TypeToken<Map<String, Object>>() { }.getType());
List<Object> body1 = (List<Object>) resp1.get("body");
assertEquals(body1.size(), 0);
//We assume allPackages list has been refreshed before sorting
helium.getAllPackageInfo();
String postRequestJson = "[name2, name1]";
PostMethod post = httpPost("/helium/order/visualization", postRequestJson);
assertThat(post, isAllowed());
post.releaseConnection();
GetMethod get2 = httpGet("/helium/order/visualization");
assertThat(get2, isAllowed());
Map<String, Object> resp2 = gson.fromJson(get2.getResponseBodyAsString(),
new TypeToken<Map<String, Object>>() { }.getType());
List<Object> body2 = (List<Object>) resp2.get("body");
assertEquals(body2.size(), 2);
assertEquals(body2.get(0), "name2");
assertEquals(body2.get(1), "name1");
}
/**
* Processes a SOAP fault, as determined by an HTTP 500 status code, response.
*
* @param httpMethod the HTTP method used to send the request and receive the response
* @param messageContext current messages context
*
* @throws SOAPClientException thrown if the response can not be read from the {@link PostMethod}
* @throws SOAPFaultException an exception containing the SOAP fault
*/
protected void processFaultResponse(PostMethod httpMethod, SOAPMessageContext messageContext)
throws SOAPClientException, SOAPFaultException {
try {
Envelope response = unmarshallResponse(httpMethod.getResponseBodyAsStream());
messageContext.setInboundMessage(response);
List<XMLObject> faults = response.getBody().getUnknownXMLObjects(Fault.DEFAULT_ELEMENT_NAME);
if (faults.size() < 1) {
throw new SOAPClientException("HTTP status code was 500 but SOAP response did not contain a Fault");
}
Fault fault = (Fault) faults.get(0);
log.debug("SOAP fault code {} with message {}", fault.getCode().getValue(), fault.getMessage().getValue());
SOAPFaultException faultException = new SOAPFaultException("SOAP Fault: " + fault.getCode().getValue()
+ " Fault Message: " + fault.getMessage().getValue());
faultException.setFault(fault);
throw faultException;
} catch (IOException e) {
throw new SOAPClientException("Unable to read response", e);
}
}
/**
* 设置请求参数
* @param method
* @param params
*/
private static void setParams(PostMethod method,Map<String, String> params) {
//校验参数
if(params==null||params.size()==0){
return;
}
Set<String> paramsKeys = params.keySet();
Iterator<String> iterParams = paramsKeys.iterator();
while(iterParams.hasNext()){
String key = iterParams.next();
method.addParameter(key, params.get(key));
}
}
public String getAccessToken(String username, String password) {
logger.debug("IN");
try {
PostMethod httppost = createPostMethodForAccessToken();
httppost.setParameter("grant_type", "password");
httppost.setParameter("username", username);
httppost.setParameter("password", password);
httppost.setParameter("client_id", config.getProperty("CLIENT_ID"));
return sendHttpPost(httppost);
} catch (Exception e) {
throw new SpagoBIRuntimeException("Error while trying to get access token from OAuth2 provider", e);
} finally {
logger.debug("OUT");
}
}
private static HttpMethodBase getMethod(HttpMethod method, String address) {
String addr = address;
if (method.equals(HttpMethod.Delete)) {
return new DeleteMethod(addr);
}
if (method.equals(HttpMethod.Post)) {
return new PostMethod(addr);
}
if (method.equals(HttpMethod.Get)) {
return new GetMethod(addr);
}
if (method.equals(HttpMethod.Put)) {
return new PutMethod(addr);
}
Assert.assertUnreachable("method doesn't exist");
return null;
}
public HttpResponse post(final RequestContext rq, final String scope, final int version, final String entityCollectionName, final Object entityId,
final String relationCollectionName, final Object relationshipEntityId, final String body, String contentType, final Map<String, String> params) throws IOException
{
RestApiEndpoint endpoint = new RestApiEndpoint(rq.getNetworkId(), scope, version, entityCollectionName, entityId, relationCollectionName,
relationshipEntityId, params);
String url = endpoint.getUrl();
PostMethod req = new PostMethod(url.toString());
if (body != null)
{
if (contentType == null || contentType.isEmpty())
{
contentType = "application/json";
}
StringRequestEntity requestEntity = new StringRequestEntity(body, contentType, "UTF-8");
req.setRequestEntity(requestEntity);
}
return submitRequest(req, rq);
}
public void post(){
String requesturl = "http://www.tuling123.com/openapi/api";
PostMethod postMethod = new PostMethod(requesturl);
String APIKEY = "4b441cb500f431adc6cc0cb650b4a5d0";
String INFO ="北京时间";
NameValuePair nvp1=new NameValuePair("key",APIKEY);
NameValuePair nvp2=new NameValuePair("info",INFO);
NameValuePair[] data = new NameValuePair[2];
data[0]=nvp1;
data[1]=nvp2;
postMethod.setRequestBody(data);
postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8");
try {
byte[] responseBody = executeMethod(postMethod,10000);
String content=new String(responseBody ,"utf-8");
log.info(content);
}catch (Exception e){
log.error(""+e.getLocalizedMessage());
}finally {
postMethod.releaseConnection();
}
}
@Test
public void testUpdateCatalogEntryQuery() throws IOException {
final HttpClient c = loginWithCookie("administrator", "olat");
final URI uri = UriBuilder.fromUri(getContextURI()).path("catalog").path(entry2.getKey().toString()).build();
final PostMethod method = createPost(uri, MediaType.APPLICATION_JSON, true);
method.setQueryString(new NameValuePair[] { new NameValuePair("name", "Entry-2-b"), new NameValuePair("description", "Entry-description-2-b"),
new NameValuePair("type", String.valueOf(CatalogEntry.TYPE_NODE)) });
final int code = c.executeMethod(method);
assertEquals(200, code);
final String body = method.getResponseBodyAsString();
method.releaseConnection();
final CatalogEntryVO vo = parse(body, CatalogEntryVO.class);
assertNotNull(vo);
final CatalogEntry updatedEntry = catalogService.loadCatalogEntry(entry2);
assertEquals("Entry-2-b", updatedEntry.getName());
assertEquals("Entry-description-2-b", updatedEntry.getDescription());
}
private void addParams( PostMethod postMethod, Map<String, String> parameterizedMap){
for (Iterator it = model.getParameters().entrySet().iterator(); it.hasNext();) {
Map.Entry me = (Map.Entry) it.next();
String key = (String) me.getKey();
List values = (List) me.getValue();
StringBuilder sb = new StringBuilder();
int cnt = 0;
for (Iterator it2 = values.iterator(); it2.hasNext();) {
String val = (String) it2.next();
if (cnt != 0) {
sb.append(",");
}
sb.append(val);
cnt++;
}
String parameterizedVal = ParseUtils.getParametizedArg(sb.toString(), parameterizedMap);
postMethod.setParameter(key, parameterizedVal);
}
}
/**
* Sending a message without mentioning Content Type and check the body part at the listening port
* <p/>
* Public JIRA: WSO2 Carbon/CARBON-6029
* Responses With No Content-Type Header not handled properly
* <p/>
* Test Artifacts: ESB Sample 0
*
* @throws Exception - if the scenario fail
*/
@SetEnvironment(executionEnvironments = { ExecutionEnvironment.ALL })
@Test(groups = "wso2.esb")
public void testMessageWithoutContentType() throws Exception {
// Get target URL
String strURL = getMainSequenceURL();
// Get SOAP action
String strSoapAction = "getQuote";
// Get file to be posted
String strXMLFilename =
FrameworkPathUtil.getSystemResourceLocation() + "artifacts" + File.separator + "ESB" + File.separator
+ "synapseconfig" + File.separator + "messagewithoutcontent" + File.separator + "request.xml";
File input = new File(strXMLFilename);
// Prepare HTTP post
PostMethod post = new PostMethod(strURL);
// Request content will be retrieved directly
// from the input stream
RequestEntity entity = new FileRequestEntity(input, "text/xml");
post.setRequestEntity(entity);
// consult documentation for your web service
post.setRequestHeader("SOAPAction", strSoapAction);
// Get HTTP client
HttpClient httpclient = new HttpClient();
// Execute request
try {
int result = httpclient.executeMethod(post);
// Display status code
log.info("Response status code: " + result);
// Display response
log.info("Response body: ");
log.info(post.getResponseBodyAsString());
} finally {
// Release current connection to the connection pool once you are done
post.releaseConnection();
}
}
/**
* Send a POST request to the endpoint "without payload" via a proxy service.
* If chunking is disabled and if there is a content aware mediator in mediation path
* Message will not send out to the endpoint. With the patch Message should send out
* so there should be a response at the client side.
*
* @throws Exception
*/
@SetEnvironment(executionEnvironments = { ExecutionEnvironment.ALL })
@Test(groups = "wso2.esb")
public void testMessageWithoutContentType() throws Exception {
// Get target URL
String strURL = getProxyServiceURLHttp(PROXY_SERVICE_NAME);
// Get SOAP action
String strSoapAction = "urn:getQuote";
// Prepare HTTP post
PostMethod post = new PostMethod(strURL);
// consult documentation for your web service
post.setRequestHeader("SOAPAction", strSoapAction);
// Get HTTP client
HttpClient httpclient = new HttpClient();
// Execute request
try {
//without the patch POST request without body it not going out from the ESB.
//if we receive any response from backend test is successful.
int result = httpclient.executeMethod(post);
// Display status code
log.info("Response status code: " + result);
// http head method should return a 500 error
assertTrue(result == 500);
} finally {
// Release current connection to the connection pool once you are done
post.releaseConnection();
}
}
protected static PostMethod httpPost(String path, String request, String user, String pwd)
throws IOException {
LOG.info("Connecting to {}", URL + path);
HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod(URL + path);
postMethod.setRequestBody(request);
postMethod.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
if (userAndPasswordAreNotBlank(user, pwd)) {
postMethod.setRequestHeader("Cookie", "JSESSIONID=" + getCookie(user, pwd));
}
httpClient.executeMethod(postMethod);
LOG.info("{} - {}", postMethod.getStatusCode(), postMethod.getStatusText());
return postMethod;
}
@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.");
}
void addToCollection(final ClientCollection col) throws ProponoException {
setCollection(col);
final EntityEnclosingMethod method = new PostMethod(getCollection().getHrefResolved());
addAuthentication(method);
final StringWriter sw = new StringWriter();
int code = -1;
try {
Atom10Generator.serializeEntry(this, sw);
method.setRequestEntity(new StringRequestEntity(sw.toString(), null, null));
method.setRequestHeader("Content-type", "application/atom+xml; charset=utf-8");
getHttpClient().executeMethod(method);
final InputStream is = method.getResponseBodyAsStream();
code = method.getStatusCode();
if (code != 200 && code != 201) {
throw new ProponoException("ERROR HTTP status=" + code + " : " + Utilities.streamToString(is));
}
final Entry romeEntry = Atom10Parser.parseEntry(new InputStreamReader(is), getCollection().getHrefResolved(), Locale.US);
BeanUtils.copyProperties(this, romeEntry);
} catch (final Exception e) {
final String msg = "ERROR: saving entry, HTTP code: " + code;
LOG.debug(msg, e);
throw new ProponoException(msg, e);
} finally {
method.releaseConnection();
}
final Header locationHeader = method.getResponseHeader("Location");
if (locationHeader == null) {
LOG.warn("WARNING added entry, but no location header returned");
} else if (getEditURI() == null) {
final List<Link> links = getOtherLinks();
final Link link = new Link();
link.setHref(locationHeader.getValue());
link.setRel("edit");
links.add(link);
setOtherLinks(links);
}
}
@Override
public HttpMethodBase prepareMethod(String url, ApiRequest request) {
PostMethod postMethod = new PostMethod(url);
postMethod = addRequestHeaders(request.getHeaders(), postMethod);
postMethod = addRequestParameters(request.getParameters(), postMethod);
return postMethod;
}