use of org.apache.commons.httpclient.methods.StringRequestEntity in project camel by apache.
the class UndertowMethodRestricTest method testProperHttpMethod.
@Test
public void testProperHttpMethod() throws Exception {
HttpClient httpClient = new HttpClient();
PostMethod httpPost = new PostMethod(url);
StringRequestEntity reqEntity = new StringRequestEntity("This is a test", null, null);
httpPost.setRequestEntity(reqEntity);
int status = httpClient.executeMethod(httpPost);
assertEquals(200, status);
String result = httpPost.getResponseBodyAsString();
assertEquals("This is a test response", result);
}
use of org.apache.commons.httpclient.methods.StringRequestEntity in project openhab1-addons by openhab.
the class Connection method sendCommand.
/**
* Send a command to the Particle REST API (convenience function).
*
* @param device
* the device context, or <code>null</code> if not needed for this command.
* @param funcName
* the function name to call, or variable/field to retrieve if <code>command</code> is
* <code>null</code>.
* @param user
* the user name to use in Basic Authentication if the funcName would require Basic Authentication.
* @param pass
* the password to use in Basic Authentication if the funcName would require Basic Authentication.
* @param command
* the command to send to the API.
* @param proc
* a callback object that receives the status code and response body, or <code>null</code> if not
* needed.
*/
public void sendCommand(AbstractDevice device, String funcName, String user, String pass, String command, HttpResponseHandler proc) {
String url = null;
String httpMethod = null;
String content = null;
String contentType = null;
Properties headers = new Properties();
logger.trace("sendCommand: funcName={}", funcName);
switch(funcName) {
case "createToken":
httpMethod = HTTP_POST;
url = TOKEN_URL;
content = command;
contentType = APPLICATION_FORM_URLENCODED;
break;
case "deleteToken":
httpMethod = HTTP_DELETE;
url = String.format(ACCESS_TOKENS_URL, tokens.accessToken);
break;
case "getDevices":
httpMethod = HTTP_GET;
url = String.format(GET_DEVICES_URL, tokens.accessToken);
break;
default:
url = String.format(DEVICE_FUNC_URL, device.getId(), funcName, tokens.accessToken);
if (command == null) {
// retrieve a variable
httpMethod = HTTP_GET;
} else {
// call a function
httpMethod = HTTP_POST;
content = command;
contentType = APPLICATION_JSON;
}
break;
}
HttpClient client = new HttpClient();
if (!url.contains("access_token=")) {
Credentials credentials = new UsernamePasswordCredentials(user, pass);
client.getParams().setAuthenticationPreemptive(true);
client.getState().setCredentials(AuthScope.ANY, credentials);
}
HttpMethod method = createHttpMethod(httpMethod, url);
method.getParams().setSoTimeout(timeout);
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
for (String httpHeaderKey : headers.stringPropertyNames()) {
method.addRequestHeader(new Header(httpHeaderKey, headers.getProperty(httpHeaderKey)));
logger.trace("Header key={}, value={}", httpHeaderKey, headers.getProperty(httpHeaderKey));
}
try {
// add content if a valid method is given ...
if (method instanceof EntityEnclosingMethod && content != null) {
EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method;
eeMethod.setRequestEntity(new StringRequestEntity(content, contentType, null));
logger.trace("content='{}', contentType='{}'", content, contentType);
}
if (logger.isDebugEnabled()) {
try {
logger.debug("About to execute '{}'", method.getURI());
} catch (URIException e) {
logger.debug(e.getMessage());
}
}
int statusCode = client.executeMethod(method);
if (statusCode >= HttpStatus.SC_BAD_REQUEST) {
logger.debug("Method failed: " + method.getStatusLine());
}
String responseBody = IOUtils.toString(method.getResponseBodyAsStream());
if (!responseBody.isEmpty()) {
logger.debug("Body of response: {}", responseBody);
}
if (proc != null) {
proc.handleResponse(statusCode, responseBody);
}
} catch (HttpException he) {
logger.warn("{}", he);
} catch (IOException ioe) {
logger.debug("{}", ioe);
} finally {
method.releaseConnection();
}
}
use of org.apache.commons.httpclient.methods.StringRequestEntity in project camel by apache.
the class HttpRouteTest method testPostXMLMessage.
@Test
public void testPostXMLMessage() throws Exception {
HttpClient client = new HttpClient();
PostMethod post = new PostMethod("http://localhost:" + port1 + "/postxml");
StringRequestEntity entity = new StringRequestEntity(POST_MESSAGE, "application/xml", "UTF-8");
post.setRequestEntity(entity);
client.executeMethod(post);
InputStream response = post.getResponseBodyAsStream();
String out = context.getTypeConverter().convertTo(String.class, response);
assertEquals("Get a wrong output ", "OK", out);
}
use of org.apache.commons.httpclient.methods.StringRequestEntity in project zm-mailbox by Zimbra.
the class ElasticSearchConnector method executeMethod.
public int executeMethod(HttpMethod method) throws IndexStoreException, IOException {
String reqBody = "";
if (ZimbraLog.elasticsearch.isTraceEnabled() && method instanceof EntityEnclosingMethod) {
EntityEnclosingMethod eem = (EntityEnclosingMethod) method;
RequestEntity re = eem.getRequestEntity();
if (re instanceof StringRequestEntity) {
StringRequestEntity sre = (StringRequestEntity) re;
reqBody = Strings.nullToEmpty(sre.getContent());
if (reqBody.length() > 0) {
reqBody = String.format("\nREQUEST BODY=%s", reqBody);
}
}
}
try {
HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
statusCode = client.executeMethod(method);
} catch (ConnectException ce) {
throw new ZimbraElasticSearchDownException(ce);
} catch (NoHttpResponseException nhre) {
// them after retrying a number of times.
throw new ZimbraElasticSearchNoResponseException(nhre);
}
body = method.getResponseBodyAsString();
ZimbraLog.elasticsearch.trace("ElasticSearch request:%s %s - statusCode=%d%s\nRESPONSE BODY=%s", method.getName(), method.getURI(), statusCode, reqBody, body);
return statusCode;
}
use of org.apache.commons.httpclient.methods.StringRequestEntity in project Mvp-Rxjava-Retrofit-dagger2 by pengMaster.
the class MediaRecordPresenter method downLoadRelationMedia.
/**
* 下载关联视频
*
* @param taken
* @param recorderCode
*/
private void downLoadRelationMedia(final String recorderCode, final String taken, final String id) {
ThreadUtils.runThread(new Runnable() {
@Override
public void run() {
HttpClient httpClient = new HttpClient();
Map msg = new HashMap();
msg.put("recorderCode", recorderCode);
// msg.put("startDate", "2017-01-25 00:00:00");
// msg.put("endDate", "2017-10-25 23:59:59");
String params = new Gson().toJson(msg);
StringRequestEntity paramEntity = null;
try {
paramEntity = new StringRequestEntity(params, "application/json", "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
PostMethod postMethod = new PostMethod(Api.GET_RELATION_MEDIA + "?token=" + taken);
postMethod.setRequestEntity(paramEntity);
try {
httpClient.executeMethod(postMethod);
} catch (IOException e) {
e.printStackTrace();
}
try {
InputStream inputStream = postMethod.getResponseBodyAsStream();
final String relationMedia = convertStreamToString(inputStream);
ThreadUtils.runInMainThread(new Runnable() {
@Override
public void run() {
Bundle bundle = new Bundle();
bundle.putString("resultRelationMedia", relationMedia);
bundle.putString("superviseId", id);
bundle.putString("recorderCode", recorderCode);
mRootView.startRelationMedia(bundle);
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
Aggregations