下面列出了怎么用org.apache.commons.httpclient.methods.StringRequestEntity的API类实例代码及写法,或者点击链接到github查看源代码。
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();
}
}
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);
}
}
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 = "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");
}
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);
}
@NotNull
private static Map<String, URL> fetchUploadUrlFromServer(@NotNull final HttpClient httpClient,
@NotNull final AgentRunningBuild build,
@NotNull final Collection<String> s3ObjectKeys) throws IOException {
try {
final PostMethod post = new PostMethod(targetUrl(build));
post.addRequestHeader("User-Agent", "TeamCity Agent");
post.setRequestEntity(new StringRequestEntity(S3PreSignUrlHelper.writeS3ObjectKeys(s3ObjectKeys), APPLICATION_XML, UTF_8));
post.setDoAuthentication(true);
final String responseBody = HttpClientCloseUtil.executeReleasingConnectionAndReadResponseBody(httpClient, post);
return S3PreSignUrlHelper.readPreSignUrlMapping(responseBody);
} catch (HttpClientCloseUtil.HttpErrorCodeException e) {
LOG.debug("Failed resolving S3 pre-signed URL for build " + build.describe(false) + " . Response code " + e.getResponseCode());
return Collections.emptyMap();
}
}
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);
}
}
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 = "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");
}
@Override
public void send() {
HttpClient client = new HttpClient();
PostMethod post = new PostMethod(endpoint);
post.setRequestHeader("Content-Type", "application/json; charset=utf-8");
Map<String, String> values = new HashMap<String, String>();
values.put("title", title);
values.put("text", content + "\n\n" + extraMessage);
values.put("url", url);
values.put("priority", priority);
try {
post.setRequestEntity(new StringRequestEntity(JSONObject.fromObject(values).toString(),
"application/json", "UTF-8"));
client.executeMethod(post);
} catch (IOException e) {
LOGGER.severe("Error while sending notification: " + e.getMessage());
e.printStackTrace();
}
}
@Override
public void sendStats(Map<String, Long> stats, String uuid, String olvVersion, String javaVersion) {
String r = stats
.entrySet()
.stream()
.sorted(Comparator.comparing(Map.Entry::getKey))
.map(kv -> kv.getKey() + "=" + kv.getValue()).collect(Collectors.joining("\n"));
HttpClient httpClient = new HttpClient();
PostMethod method = new PostMethod(SEND_URL);
try {
method.setRequestEntity(new StringRequestEntity(r, "text/plain", "UTF-8"));
method.addRequestHeader("uuid", uuid);
method.addRequestHeader("olvVersion", olvVersion);
method.addRequestHeader("javaVersion", javaVersion);
httpClient.executeMethod(method);
} catch (Exception e) {
//User is not interested in issues with sending report
LOGGER.warn("Can't send stats to server", e);
}
}
private static void sendMessage() throws IOException, JsonProcessingException, JsonGenerationException,
JsonMappingException, UnsupportedEncodingException, HttpException {
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> m = new HashMap<String, Object>();
m.put("si", "12345");
m.put("ct", System.currentTimeMillis());
String payload = mapper.writeValueAsString(m);
HttpClient client = new HttpClient();
PostMethod method = new PostMethod("http://localhost:8080/tracking/ingest/PulsarRawEvent");
// method.addRequestHeader("Accept-Encoding", "gzip,deflate,sdch");
method.setRequestEntity(new StringRequestEntity(payload, "application/json", "UTF-8"));
int status = client.executeMethod(method);
System.out.println(Arrays.toString(method.getResponseHeaders()));
System.out.println("Status code: " + status + ", Body: " + method.getResponseBodyAsString());
}
@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");
}
@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);
}
@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");
}
@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 TestRailResponse httpPostInt(String path, String payload)
throws UnsupportedEncodingException, IOException, HTTPException {
TestRailResponse result;
PostMethod post = new PostMethod(host + "/" + path);
HttpClient httpclient = setUpHttpClient(post);
try {
StringRequestEntity requestEntity = new StringRequestEntity(
payload,
"application/json",
"UTF-8"
);
post.setRequestEntity(requestEntity);
Integer status = httpclient.executeMethod(post);
String body = new String(post.getResponseBody(), post.getResponseCharSet());
result = new TestRailResponse(status, body);
} finally {
post.releaseConnection();
}
return result;
}
protected <T> String executeUpdateObject(final T newObject, final String uri,
final Map<String, String> parameters) throws BigSwitchBcfApiException,
IllegalArgumentException{
checkInvariants();
PutMethod pm = (PutMethod)createMethod("put", uri, _port);
setHttpHeader(pm);
try {
pm.setRequestEntity(new StringRequestEntity(gson.toJson(newObject), CONTENT_JSON, null));
} catch (UnsupportedEncodingException e) {
throw new BigSwitchBcfApiException("Failed to encode json request body", e);
}
executeMethod(pm);
String hash = checkResponse(pm, "BigSwitch HTTP update failed: ");
pm.releaseConnection();
return hash;
}
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();
}
}
private void addDashboard(String dashboard) throws MonitorException {
// format url
String url = String.format("%s/%s", grafanaApiUrl, GrafanaDashboardServiceImpl.GRAFANA_ADD_DASHBOARD_URI);
PostMethod method = new PostMethod(url);
try {
// request body
method.setRequestEntity(new StringRequestEntity(dashboard, "application/json", CharEncoding.UTF_8));
doHttpAPI(method);
} catch (UnsupportedEncodingException e) {
new MonitorException(e);
}
}
public void setRequestBody(String body)
{
try
{
requestBody = new StringRequestEntity(body, getContentType(), "UTF-8");
}
catch (UnsupportedEncodingException e) {} // Can't occur
}
protected JSONObject postQuery(HttpClient httpClient, String url, JSONObject body) throws UnsupportedEncodingException,
IOException, HttpException, URIException, JSONException
{
PostMethod post = new PostMethod(url);
if (body.toString().length() > DEFAULT_SAVEPOST_BUFFER)
{
post.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
}
StringRequestEntity requestEntity = new StringRequestEntity(body.toString(), "application/json", "UTF-8");
post.setRequestEntity(requestEntity);
try
{
httpClient.executeMethod(post);
if(post.getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY || post.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY)
{
Header locationHeader = post.getResponseHeader("location");
if (locationHeader != null)
{
String redirectLocation = locationHeader.getValue();
post.setURI(new URI(redirectLocation, true));
httpClient.executeMethod(post);
}
}
if (post.getStatusCode() != HttpServletResponse.SC_OK)
{
throw new LuceneQueryParserException("Request failed " + post.getStatusCode() + " " + url.toString());
}
Reader reader = new BufferedReader(new InputStreamReader(post.getResponseBodyAsStream(), post.getResponseCharSet()));
// TODO - replace with streaming-based solution e.g. SimpleJSON ContentHandler
JSONObject json = new JSONObject(new JSONTokener(reader));
return json;
}
finally
{
post.releaseConnection();
}
}
@Override
protected ServerStatus _doIt() {
try {
/* create cloud foundry application */
URI targetURI = URIUtil.toURI(target.getUrl());
URI routesURI = targetURI.resolve("/v2/routes"); //$NON-NLS-1$
PostMethod createRouteMethod = new PostMethod(routesURI.toString());
ServerStatus confStatus = HttpUtil.configureHttpMethod(createRouteMethod, target.getCloud());
if (!confStatus.isOK())
return confStatus;
/* set request body */
JSONObject routeRequest = new JSONObject();
routeRequest.put(CFProtocolConstants.V2_KEY_SPACE_GUID, target.getSpace().getCFJSON().getJSONObject(CFProtocolConstants.V2_KEY_METADATA).getString(CFProtocolConstants.V2_KEY_GUID));
routeRequest.put(CFProtocolConstants.V2_KEY_HOST, hostName);
routeRequest.put(CFProtocolConstants.V2_KEY_DOMAIN_GUID, domain.getGuid());
createRouteMethod.setRequestEntity(new StringRequestEntity(routeRequest.toString(), "application/json", "utf-8")); //$NON-NLS-1$//$NON-NLS-2$
createRouteMethod.setQueryString("inline-relations-depth=1"); //$NON-NLS-1$
ServerStatus createRouteStatus = HttpUtil.executeMethod(createRouteMethod);
if (!createRouteStatus.isOK())
return createRouteStatus;
route = new Route().setCFJSON(createRouteStatus.getJsonData());
return createRouteStatus;
} catch (Exception e) {
String msg = NLS.bind("An error occured when performing operation {0}", commandName); //$NON-NLS-1$
logger.error(msg, e);
return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
}
}
public ServerStatus _doIt() {
try {
URI targetURI = URIUtil.toURI(target.getUrl());
String appUrl = this.app.getAppJSON().getString("url");
URI appURI = targetURI.resolve(appUrl);
PutMethod stopMethod = new PutMethod(appURI.toString());
ServerStatus confStatus = HttpUtil.configureHttpMethod(stopMethod, target.getCloud());
if (!confStatus.isOK())
return confStatus;
stopMethod.setQueryString("inline-relations-depth=1");
JSONObject stopComand = new JSONObject();
stopComand.put("console", true);
stopComand.put("state", "STOPPED");
StringRequestEntity requestEntity = new StringRequestEntity(stopComand.toString(), CFProtocolConstants.JSON_CONTENT_TYPE, "UTF-8");
stopMethod.setRequestEntity(requestEntity);
GetAppCommand.expire(target, app.getName());
return HttpUtil.executeMethod(stopMethod);
} catch (Exception e) {
String msg = NLS.bind("An error occured when performing operation {0}", commandName); //$NON-NLS-1$
logger.error(msg, e);
return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, e);
}
}
private StringRequestEntity getAuthenticationRequst(AuthenticationRequest authenticationRequest)
throws IOException {
final String data = JSONUtil.toJSON(new AuthenticationRequestWrapper(
authenticationRequest));
if (LOG.isDebugEnabled()) {
LOG.debug("Authenticating with " + authenticationRequest);
}
return toJsonEntity(data);
}
public HttpResponse post(final Class<?> c, final RequestContext rq, final Object entityId, final Object relationshipEntityId, final String body)
throws IOException
{
RestApiEndpoint endpoint = new RestApiEndpoint(c, rq.getNetworkId(), entityId, relationshipEntityId, null);
String url = endpoint.getUrl();
PostMethod req = new PostMethod(url.toString());
if (body != null)
{
StringRequestEntity requestEntity = new StringRequestEntity(body, "application/json", "UTF-8");
req.setRequestEntity(requestEntity);
}
return submitRequest(req, rq);
}
public HttpResponse post(final RequestContext rq, final String urlSuffix, String body) throws IOException
{
RestApiEndpoint endpoint = new RestApiEndpoint(rq.getNetworkId(), urlSuffix, null);
String url = endpoint.getUrl();
PostMethod req = new PostMethod(url.toString());
if (body != null)
{
StringRequestEntity requestEntity = new StringRequestEntity(body, "application/json", "UTF-8");
req.setRequestEntity(requestEntity);
}
return submitRequest(req, rq);
}
public HttpResponse put(final Class<?> c, final RequestContext rq, final Object entityId, final Object relationshipEntityId, final String body)
throws IOException
{
RestApiEndpoint endpoint = new RestApiEndpoint(c, rq.getNetworkId(), entityId, relationshipEntityId, null);
String url = endpoint.getUrl();
PutMethod req = new PutMethod(url);
if (body != null)
{
StringRequestEntity requestEntity = new StringRequestEntity(body, "application/json", "UTF-8");
req.setRequestEntity(requestEntity);
}
return submitRequest(req, rq);
}