类org.apache.commons.httpclient.methods.RequestEntity源码实例Demo

下面列出了怎么用org.apache.commons.httpclient.methods.RequestEntity的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: swellrt   文件: SolrWaveIndexerImpl.java
private void postUpdateToSolr(ReadableWaveletData wavelet, JsonArray docsJson) {
  PostMethod postMethod =
      new PostMethod(solrBaseUrl + "/update/json?commit=true");
  try {
    RequestEntity requestEntity =
        new StringRequestEntity(docsJson.toString(), "application/json", "UTF-8");
    postMethod.setRequestEntity(requestEntity);

    HttpClient httpClient = new HttpClient();
    int statusCode = httpClient.executeMethod(postMethod);
    if (statusCode != HttpStatus.SC_OK) {
      throw new IndexException(wavelet.getWaveId().serialise());
    }
  } catch (IOException e) {
    throw new IndexException(String.valueOf(wavelet.getWaveletId()), e);
  } finally {
    postMethod.releaseConnection();
  }
}
 
@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");
}
 
@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");
}
 
@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");

}
 
@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");
}
 
源代码7 项目: davmail   文件: TestCaldav.java
SearchReportMethod(String path, final byte[] content) {
    super(path);
    setRequestEntity(new RequestEntity() {

        public boolean isRepeatable() {
            return true;
        }

        public void writeRequest(OutputStream outputStream) throws IOException {
            outputStream.write(content);
        }

        public long getContentLength() {
            return content.length;
        }

        public String getContentType() {
            return "text/xml;charset=UTF-8";
        }
    });
}
 
源代码8 项目: lams   文件: HttpSOAPClient.java
/**
 * Creates the request entity that makes up the POST message body.
 * 
 * @param message message to be sent
 * @param charset character set used for the message
 * 
 * @return request entity that makes up the POST message body
 * 
 * @throws SOAPClientException thrown if the message could not be marshalled
 */
protected RequestEntity createRequestEntity(Envelope message, Charset charset) throws SOAPClientException {
    try {
        Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(message);
        ByteArrayOutputStream arrayOut = new ByteArrayOutputStream();
        OutputStreamWriter writer = new OutputStreamWriter(arrayOut, charset);

        if (log.isDebugEnabled()) {
            log.debug("Outbound SOAP message is:\n" + XMLHelper.prettyPrintXML(marshaller.marshall(message)));
        }
        XMLHelper.writeNode(marshaller.marshall(message), writer);
        return new ByteArrayRequestEntity(arrayOut.toByteArray(), "text/xml");
    } catch (MarshallingException e) {
        throw new SOAPClientException("Unable to marshall SOAP envelope", e);
    }
}
 
@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");
}
 
@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");

}
 
@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");
}
 
源代码12 项目: olat   文件: GroupMgmtITCase.java
@Test
public void testUpdateCourseGroup() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final GroupVO vo = new GroupVO();
    vo.setKey(g1.getKey());
    vo.setName("rest-g1-mod");
    vo.setDescription("rest-g1 description");
    vo.setMinParticipants(g1.getMinParticipants());
    vo.setMaxParticipants(g1.getMaxParticipants());
    vo.setType(g1.getType());

    final String stringuifiedAuth = stringuified(vo);
    final RequestEntity entity = new StringRequestEntity(stringuifiedAuth, MediaType.APPLICATION_JSON, "UTF-8");
    final String request = "/groups/" + g1.getKey();
    final PostMethod method = createPost(request, MediaType.APPLICATION_JSON, true);
    method.setRequestEntity(entity);
    final int code = c.executeMethod(method);
    assertTrue(code == 200 || code == 201);

    final BusinessGroup bg = businessGroupService.loadBusinessGroup(g1.getKey(), false);
    assertNotNull(bg);
    assertEquals(bg.getKey(), vo.getKey());
    assertEquals(bg.getName(), "rest-g1-mod");
    assertEquals(bg.getDescription(), "rest-g1 description");
}
 
源代码13 项目: olat   文件: CourseGroupMgmtITCase.java
@Test
public void testBasicSecurityPutCall() throws IOException {
    final HttpClient c = loginWithCookie("rest-c-g-3", "A6B7C8");

    final GroupVO vo = new GroupVO();
    vo.setName("hello dont put");
    vo.setDescription("hello description dont put");
    vo.setMinParticipants(new Integer(-1));
    vo.setMaxParticipants(new Integer(-1));

    final String stringuifiedAuth = stringuified(vo);
    final RequestEntity entity = new StringRequestEntity(stringuifiedAuth, MediaType.APPLICATION_JSON, "UTF-8");
    final String request = "/repo/courses/" + course.getResourceableId() + "/groups";
    final PutMethod method = createPut(request, MediaType.APPLICATION_JSON, true);
    method.setRequestEntity(entity);
    final int code = c.executeMethod(method);

    assertEquals(401, code);
}
 
源代码14 项目: olat   文件: GroupMgmtITCase.java
@Test
public void testUpdateCourseGroup() throws IOException {
    final HttpClient c = loginWithCookie("administrator", "olat");

    final GroupVO vo = new GroupVO();
    vo.setKey(g1.getKey());
    vo.setName("rest-g1-mod");
    vo.setDescription("rest-g1 description");
    vo.setMinParticipants(g1.getMinParticipants());
    vo.setMaxParticipants(g1.getMaxParticipants());
    vo.setType(g1.getType());

    final String stringuifiedAuth = stringuified(vo);
    final RequestEntity entity = new StringRequestEntity(stringuifiedAuth, MediaType.APPLICATION_JSON, "UTF-8");
    final String request = "/groups/" + g1.getKey();
    final PostMethod method = createPost(request, MediaType.APPLICATION_JSON, true);
    method.setRequestEntity(entity);
    final int code = c.executeMethod(method);
    assertTrue(code == 200 || code == 201);

    final BusinessGroup bg = businessGroupService.loadBusinessGroup(g1.getKey(), false);
    assertNotNull(bg);
    assertEquals(bg.getKey(), vo.getKey());
    assertEquals(bg.getName(), "rest-g1-mod");
    assertEquals(bg.getDescription(), "rest-g1 description");
}
 
源代码15 项目: olat   文件: CourseGroupMgmtITCase.java
@Test
public void testBasicSecurityPutCall() throws IOException {
    final HttpClient c = loginWithCookie("rest-c-g-3", "A6B7C8");

    final GroupVO vo = new GroupVO();
    vo.setName("hello dont put");
    vo.setDescription("hello description dont put");
    vo.setMinParticipants(new Integer(-1));
    vo.setMaxParticipants(new Integer(-1));

    final String stringuifiedAuth = stringuified(vo);
    final RequestEntity entity = new StringRequestEntity(stringuifiedAuth, MediaType.APPLICATION_JSON, "UTF-8");
    final String request = "/repo/courses/" + course.getResourceableId() + "/groups";
    final PutMethod method = createPut(request, MediaType.APPLICATION_JSON, true);
    method.setRequestEntity(entity);
    final int code = c.executeMethod(method);

    assertEquals(401, code);
}
 
private void postUpdateToSolr(ReadableWaveletData wavelet, JsonArray docsJson) {
  PostMethod postMethod =
      new PostMethod(solrBaseUrl + "/update/json?commit=true");
  try {
    RequestEntity requestEntity =
        new StringRequestEntity(docsJson.toString(), "application/json", "UTF-8");
    postMethod.setRequestEntity(requestEntity);

    HttpClient httpClient = new HttpClient();
    int statusCode = httpClient.executeMethod(postMethod);
    if (statusCode != HttpStatus.SC_OK) {
      throw new IndexException(wavelet.getWaveId().serialise());
    }
  } catch (IOException e) {
    throw new IndexException(String.valueOf(wavelet.getWaveletId()), e);
  } finally {
    postMethod.releaseConnection();
  }
}
 
源代码17 项目: Crucible4IDEA   文件: CrucibleSessionImpl.java
protected JsonObject buildJsonResponseForPost(@NotNull final String urlString,
                                           @NotNull final RequestEntity requestEntity) throws IOException {
  final PostMethod method = new PostMethod(urlString);
  method.setRequestEntity(requestEntity);
  executeHttpMethod(method);

  final String response = method.getResponseBodyAsString();
  try {
    return JsonParser.parseString(response).getAsJsonObject();
  }
  catch (JsonSyntaxException ex) {
    LOG.error("Malformed Json");
    LOG.error(response);
  }
  return new JsonObject();
}
 
源代码18 项目: submarine   文件: AbstractSubmarineServerTest.java
protected static PutMethod httpPut(String path, String body, String user, String pwd) throws IOException {
  LOG.info("Connecting to {}", URL + path);
  HttpClient httpClient = new HttpClient();
  PutMethod putMethod = new PutMethod(URL + path);
  putMethod.addRequestHeader("Origin", URL);
  putMethod.setRequestHeader("Content-type", "application/yaml");
  RequestEntity entity = new ByteArrayRequestEntity(body.getBytes("UTF-8"));
  putMethod.setRequestEntity(entity);
  if (userAndPasswordAreNotBlank(user, pwd)) {
    putMethod.setRequestHeader("Cookie", "JSESSIONID=" + getCookie(user, pwd));
  }
  httpClient.executeMethod(putMethod);
  LOG.info("{} - {}", putMethod.getStatusCode(), putMethod.getStatusText());
  return putMethod;
}
 
/**
 * 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();
    }
}
 
@Test(groups = "wso2.esb", description = "Test whether response HTTP status code getting correctly after callout "
        + "mediator successfully execute")
public void testHttpStatusCodeGettingSuccessfully() throws Exception {
    String endpoint = getProxyServiceURLHttp("TestCalloutHTTP_SC");
    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 {
        httpClient.executeMethod(post);
        errorLog = carbonLogReader.checkForLog("STATUS-Fault", DEFAULT_TIMEOUT) && carbonLogReader.
                checkForLog("404 Error: Not Found", DEFAULT_TIMEOUT);
        carbonLogReader.stop();
    } finally {
        post.releaseConnection();
    }

    if (!errorLog) {
        fail("Response HTTP code not return successfully.");
    }
}
 
@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.");
}
 
源代码22 项目: davmail   文件: ExchangeDavMethod.java
/**
 * Create PROPPATCH method.
 *
 * @param path           path
 */
public ExchangeDavMethod(String path) {
    super(path);
    setRequestEntity(new RequestEntity() {
        byte[] content;

        public boolean isRepeatable() {
            return true;
        }

        public void writeRequest(OutputStream outputStream) throws IOException {
            if (content == null) {
                content = generateRequestContent();
            }
            outputStream.write(content);
        }

        public long getContentLength() {
            if (content == null) {
                content = generateRequestContent();
            }
            return content.length;
        }

        public String getContentType() {
            return "text/xml;charset=UTF-8";
        }
    });
}
 
源代码23 项目: davmail   文件: RestMethod.java
public RestMethod(String uri) {
    super(uri);

    setRequestEntity(new RequestEntity() {
        byte[] content;

        public boolean isRepeatable() {
            return true;
        }

        public void writeRequest(OutputStream outputStream) throws IOException {
            if (content == null) {
                content = getJsonContent();
            }
            outputStream.write(content);
        }

        public long getContentLength() {
            if (content == null) {
                content = getJsonContent();
            }
            return content.length;
        }

        public String getContentType() {
            return "application/json; charset=UTF-8";
        }
    });
}
 
/**
 * 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();
    }
}
 
/**
 * 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();
    }
}
 
@Test(groups = "wso2.esb", description = "Test whether response HTTP status code getting correctly after callout " +
                                         "mediator successfully execute")
public void testHttpStatusCodeGettingSuccessfully() throws Exception {
    String endpoint = getProxyServiceURLHttp("TestCalloutHTTP_SC");
    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 {
        httpClient.executeMethod(post);

        LogEvent[] logs = logViewerClient.getAllRemoteSystemLogs();
        for (LogEvent logEvent : logs) {
            if (logEvent.getPriority().equals("INFO")) {
                String message = logEvent.getMessage();
                if (message.contains("STATUS-Fault") && message.contains("404 Error: Not Found")) {
                    errorLog = true;
                    break;
                }
            }
        }
    } finally {
        post.releaseConnection();
    }

    if (!errorLog) {
        fail("Response HTTP code not return successfully.");
    }
}
 
@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);

        LogEvent[] logs = logViewerClient.getAllRemoteSystemLogs();
        for (LogEvent logEvent : logs) {
            if (logEvent.getPriority().equals("ERROR")) {
                String message = logEvent.getMessage();
                if (message.contains("Unable to convert to SoapHeader Block")) {
                    errorLog = true;
                    break;
                }
            }
        }
    } finally {
        post.releaseConnection();
    }
    assertFalse(errorLog, "Mediator Hasn't invoked successfully.");
}
 
@Test(groups = "wso2.esb", description = "Testing functionality of FORCE_SC_ACCEPTED " +
                                         "- Enabled False")
public void testFORCE_SC_ACCEPTEDPropertyEnabledFalseScenario() throws Exception {
    verifyProxyServiceExistence("FORCE_SC_ACCEPTED_FalseTestProxy");

    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 {
    verifyProxyServiceExistence("FORCE_SC_ACCEPTED_TrueTestProxy");

    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");
}
 
源代码30 项目: SI   文件: Tr069DMAdapter.java
private void callPutFileApi(String fileType, String url, String filePath, String oui, String prodClass, String version) throws HttpException, IOException, HitDMException {
	org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
	
	PutMethod putMethod = new PutMethod(url);
	File input = new File(filePath);
	RequestEntity entity = new FileRequestEntity(input, "Content-Length: 1431");
	putMethod.setRequestEntity(entity);
	putMethod.setRequestHeader("fileType", fileType);
	putMethod.setRequestHeader("oui", oui);
	putMethod.setRequestHeader("productClass", prodClass);
	putMethod.setRequestHeader("version", version);
	
	client.executeMethod(putMethod);
	
	if (putMethod.getStatusCode() != 200) {
		String debugStr = "DM Server return:"+ putMethod.getStatusCode();
		byte[] body;
		try {
			body = putMethod.getResponseBody();
			if (body != null) {
				debugStr += "\r\nBody:"+new String(body);
			}
		} catch (Exception e) {
			debugStr += e.getMessage();
		}
		
		throw new HitDMException(putMethod.getStatusCode(), debugStr);
	}
	
}
 
 类方法
 同包方法