use of org.apache.hc.core5.http.copied.NameValuePair in project californium by eclipse.
the class Http2CoapTranslator method getCoapRequest.
/**
* Gets the coap request.
*
* Creates the CoAP request from the HTTP method and mapping it through the
* properties file. The URI is translated by extracting the part after the
* provided httpResource.
* (http://proxyname.domain:80/proxy/coap://coapserver:5683/resource
* converted in coap://coapserver:5683/resource.) It support proxy requests
* or request mapped to a local coap-server. It also support http-request
* send to this proxy using the http-proxy function itself. Though the
* primary scheme maybe tested to be http/https, the destination scheme must
* The method uses a decoder to translate the
* application/x-www-form-urlencoded format of the uri. The CoAP options are
* set translating the headers. If the HTTP message has an enclosing entity,
* it is converted to create the payload of the CoAP message; finally the
* content-type is set accordingly to the header and to the entity type.
*
* @param httpRequest the http request
* @param httpResource the http resource, if present in the uri, indicates
* the need of forwarding for the current request
* @param proxyingEnabled {@code true} to forward the request using the
* sub-path as URI, {@code false} to access a local coap
* resource.
* @return the coap request
* @throws TranslationException the translation exception
* @throws NullPointerException if one of the provided arguments is
* {@code null}.
*/
public Request getCoapRequest(Message<HttpRequest, ContentTypedEntity> httpRequest, String httpResource, boolean proxyingEnabled) throws TranslationException {
if (httpRequest == null) {
throw new NullPointerException("httpRequest must not be null!");
}
if (httpResource == null) {
throw new NullPointerException("httpResource must not be null!");
}
// get the http method
String httpMethod = httpRequest.getHead().getMethod();
// get the coap method
Code code = httpTranslator.getCoapCode(httpMethod);
// create the request -- since HTTP is reliable use CON
Request coapRequest = new Request(code, Type.CON);
// get the uri
URI uri;
try {
uri = httpRequest.getHead().getUri();
LOGGER.debug("URI <= '{}'", uri);
} catch (URISyntaxException ex) {
throw new TranslationException("Malformed uri: " + ex.getMessage());
}
if (!httpResource.startsWith("/")) {
httpResource = "/" + httpResource;
}
// if the uri contains the proxy resource name, the request should be
// forwarded and it is needed to get the real requested coap server's
// uri e.g.:
// /proxy/coap://vslab-dhcp-17.inf.ethz.ch:5684/helloWorld
// proxy resource: /proxy
// coap server: coap://vslab-dhcp-17.inf.ethz.ch:5684
// coap resource: helloWorld
String path = uri.getPath();
LOGGER.debug("URI path => '{}'", path);
if (path.startsWith(httpResource + "/")) {
path = path.substring(httpResource.length() + 1);
String target = path;
if (uri.getQuery() != null) {
target = path + "?" + uri.getQuery();
}
int index = target.indexOf(":/");
if (index > 0) {
// "coap://host" may have been normalized to "coap:/host"
index += 2;
if (target.charAt(index) != '/') {
// add /
target = target.substring(0, index) + "/" + target.substring(index);
}
}
try {
uri = new URI(target);
if (proxyingEnabled) {
// if the uri hasn't the indication of the scheme, add it
if (uri.getScheme() == null) {
throw new InvalidFieldException("Malformed uri: destination scheme missing! Use http://<proxy-host>" + httpResource + "/coap://<destination-host>/<path>");
}
// the uri will be set as a proxy-uri option
LOGGER.debug("URI destination => '{}'", target);
coapRequest.getOptions().setProxyUri(target);
} else {
if (uri.getScheme() != null) {
throw new InvalidFieldException("Malformed uri: local destination doesn't support scheme! Use http://<proxy-host>" + httpResource + "/<path>");
}
// the uri will be set as a coap-uri
target = "coap://localhost/" + target;
LOGGER.debug("URI local => '{}'", target);
coapRequest.setURI(target);
}
} catch (URISyntaxException e) {
LOGGER.warn("Malformed destination uri", e);
throw new InvalidFieldException("Malformed destination uri: " + target + "!");
}
} else if (proxyingEnabled && path.equals(httpResource)) {
String target = null;
if (uri.getQuery() != null) {
List<NameValuePair> query = WWWFormCodec.parse(uri.getQuery(), StandardCharsets.UTF_8);
for (NameValuePair arg : query) {
if (arg.getName().equalsIgnoreCase("target_uri")) {
target = arg.getValue();
break;
}
}
}
if (target == null) {
throw new InvalidFieldException("Malformed uri: target_uri is missing! Use http://<proxy-host>" + httpResource + "?target_uri=coap://<destination-host>/<path>");
}
try {
uri = new URI(target);
// if the uri hasn't the indication of the scheme, add it
if (uri.getScheme() == null) {
throw new InvalidFieldException("Malformed uri: destination scheme missing! Use http://<proxy-host>" + httpResource + "?target_uri=coap://<destination-host>/<path>");
}
// the uri will be set as a proxy-uri option
LOGGER.debug("URI destination => '{}'", target);
coapRequest.getOptions().setProxyUri(target);
} catch (URISyntaxException e) {
LOGGER.warn("Malformed destination uri", e);
throw new InvalidFieldException("Malformed destination uri: " + target + "!");
}
} else if (proxyingEnabled && uri.getScheme() != null) {
// http-server configured as http-proxy
int index = path.lastIndexOf('/');
if (0 < index) {
String scheme = path.substring(index + 1);
if (scheme.matches("\\w+:$")) {
scheme = scheme.substring(0, scheme.length() - 1);
path = path.substring(0, index);
try {
URI destination = new URI(scheme, null, uri.getHost(), uri.getPort(), path, uri.getQuery(), null);
coapRequest.getOptions().setProxyUri(destination.toASCIIString());
} catch (URISyntaxException e) {
LOGGER.debug("Malformed proxy uri", e);
throw new TranslationException("Malformed proxy uri: '" + uri + "' " + e.getMessage());
}
} else {
throw new TranslationException("Malformed proxy uri: target scheme missing! Use http://<destination-host>/<path>/<target-scheme>:");
}
} else {
throw new TranslationException("Malformed proxy uri: target scheme missing! Use http://<destination-host>/<path>/<target-scheme>:");
}
} else {
throw new IllegalArgumentException("URI '" + uri + "' doesn't match handler '" + httpResource + "'!");
}
// translate the http headers in coap options
List<Option> coapOptions = httpTranslator.getCoapOptions(httpRequest.getHead().getHeaders(), etagTranslator);
coapRequest.getOptions().addOptions(coapOptions);
// set the payload if the http entity is present
ContentTypedEntity entity = httpRequest.getBody();
httpTranslator.setCoapPayload(entity, coapRequest);
return coapRequest;
}
use of org.apache.hc.core5.http.copied.NameValuePair in project californium by eclipse.
the class CrossProtocolTranslator method getCoapOptions.
/**
* Gets the coap options starting from an array of http headers.
*
* The content-type is not handled by this method. The method iterates over
* an array of headers and for each of them tries to find a mapping in the
* properties file, if the mapping does not exists it skips the header
* ignoring it. The method handles separately certain headers which are
* translated to options (such as accept or cache-control) whose content
* should be semantically checked or requires ad-hoc translation. Otherwise,
* the headers content is translated with the appropriate format required by
* the mapped option.
*
* @param headers array of http headers
* @param etagTranslator translator for etag
* @return list of CoAP options.
* @throws NullPointerException if headers is {@code null}
*/
public List<Option> getCoapOptions(Header[] headers, EtagTranslator etagTranslator) {
if (headers == null) {
throw new NullPointerException("http header must not be null!");
}
Option accept = null;
float acceptQualifier = 0.0F;
List<Option> optionList = new LinkedList<Option>();
// iterate over the headers
for (Header header : headers) {
try {
String headerName = header.getName().toLowerCase();
// get the mapping from the property file
Integer coapOption = translationMapping.getCoapOption(headerName);
// ignore the header if not found in the properties file
if (coapOption == null) {
continue;
}
int optionNumber = coapOption;
// payload
if (optionNumber == OptionNumberRegistry.CONTENT_FORMAT) {
continue;
}
// get the value of the current header
String headerValue = header.getValue().trim();
// values
if (optionNumber == OptionNumberRegistry.ACCEPT) {
final ParserCursor cursor = new ParserCursor(0, headerValue.length());
HeaderElement[] headerElements = parser.parseElements(headerValue, cursor);
for (HeaderElement element : headerElements) {
float qualifier = 1.0F;
String mimeType = element.getName();
NameValuePair q = element.getParameterByName("q");
if (q != null) {
try {
qualifier = Float.parseFloat(q.getValue());
} catch (NumberFormatException ex) {
}
}
if (accept == null || acceptQualifier < qualifier) {
int coapContentType = MediaTypeRegistry.UNDEFINED;
String headerFragment = mimeType.trim();
if (headerFragment.contains("*")) {
int[] coapContentTypes = MediaTypeRegistry.parseWildcard(headerFragment);
if (coapContentTypes.length > 0) {
coapContentType = coapContentTypes[0];
}
} else {
coapContentType = getCoapMediaType(headerFragment, MediaTypeRegistry.UNDEFINED);
}
if (coapContentType != MediaTypeRegistry.UNDEFINED) {
accept = new Option(optionNumber, coapContentType);
acceptQualifier = qualifier;
}
}
}
} else if (optionNumber == OptionNumberRegistry.MAX_AGE) {
int maxAge = -1;
final ParserCursor cursor = new ParserCursor(0, headerValue.length());
HeaderElement[] headerElements = parser.parseElements(headerValue, cursor);
for (HeaderElement element : headerElements) {
if (element.getName().equalsIgnoreCase("no-cache")) {
maxAge = 0;
break;
} else if (element.getName().equalsIgnoreCase("max-age")) {
String value = element.getValue();
try {
maxAge = Integer.parseInt(value);
break;
} catch (NumberFormatException e) {
LOGGER.debug("Cannot convert cache control '{}' in max-age option", value, e);
}
}
}
if (maxAge >= 0) {
// create the option
Option option = new Option(optionNumber, maxAge);
optionList.add(option);
}
} else if (optionNumber == OptionNumberRegistry.ETAG) {
byte[] etag = etagTranslator.getCoapEtag(headerValue);
Option option = new Option(optionNumber, etag);
optionList.add(option);
} else if (optionNumber == OptionNumberRegistry.IF_MATCH) {
byte[] etag = etagTranslator.getCoapEtag(headerValue);
Option option = new Option(optionNumber, etag);
optionList.add(option);
} else if (optionNumber == OptionNumberRegistry.IF_NONE_MATCH) {
if (headerValue.equals("*")) {
Option option = new Option(optionNumber, Bytes.EMPTY);
optionList.add(option);
} else {
LOGGER.debug("'if-none-match' with etag '{}' is not supported!", headerValue);
}
} else if (optionNumber == OptionNumberRegistry.LOCATION_PATH) {
try {
URI uri = new URI(headerValue);
OptionSet set = new OptionSet();
String value = uri.getPath();
if (value != null) {
set.setLocationPath(value);
}
value = uri.getQuery();
if (value != null) {
set.setLocationQuery(value);
}
optionList.addAll(set.asSortedList());
} catch (URISyntaxException e) {
LOGGER.debug("'content-location' with '{}' is not supported!", headerValue, e);
} catch (IllegalArgumentException e) {
LOGGER.debug("'content-location' with '{}' is not supported!", headerValue, e);
}
} else {
// create the option
Option option = new Option(optionNumber);
switch(OptionNumberRegistry.getFormatByNr(optionNumber)) {
case INTEGER:
option.setIntegerValue(Integer.parseInt(headerValue));
break;
case OPAQUE:
option.setValue(headerValue.getBytes(ISO_8859_1));
break;
case EMPTY:
option.setValue(Bytes.EMPTY);
break;
case STRING:
default:
option.setStringValue(headerValue);
break;
}
optionList.add(option);
}
} catch (RuntimeException e) {
LOGGER.debug("Could not parse header line {}: {}", header, e.getMessage());
}
}
if (accept != null) {
optionList.add(accept);
}
return optionList;
}
use of org.apache.hc.core5.http.copied.NameValuePair in project jahia by Jahia.
the class HttpClientService method executePost.
/**
* Executes a request with POST method to the specified URL and reads the response content as a string.
*
* @param url a URL to connect to
* @param parameters the request parameter to submit; <code>null</code> if no parameters are passed
* @param headers request headers to be set for connection; <code>null</code> if no additional headers needs to be set
* @return the string representation of the URL connection response
* @throws {@link IllegalArgumentException} in case of a malformed URL
*/
public String executePost(String url, Map<String, String> parameters, Map<String, String> headers) throws IllegalArgumentException {
if (StringUtils.isEmpty(url)) {
throw new IllegalArgumentException(URL_NOT_PROVIDED);
}
if (logger.isDebugEnabled()) {
logger.debug("Asked to get content from the URL {} using POST method with parameters {}", url, parameters);
}
String content = null;
HttpPost httpMethod = new HttpPost(url);
List<NameValuePair> nvps = new ArrayList<>();
if (parameters != null && !parameters.isEmpty()) {
for (Map.Entry<String, String> param : parameters.entrySet()) {
nvps.add(new BasicNameValuePair(param.getKey(), param.getValue()));
}
}
if (headers != null && !headers.isEmpty()) {
for (Map.Entry<String, String> header : headers.entrySet()) {
httpMethod.addHeader(header.getKey(), header.getValue());
}
}
httpMethod.setEntity(new UrlEncodedFormEntity(nvps));
try (CloseableHttpResponse response = getHttpClient(url).execute(httpMethod)) {
if (response.getCode() == SC_OK) {
content = EntityUtils.toString(response.getEntity());
} else {
logger.warn("Connection to URL: {} failed with status {}", url, response.getCode());
}
} catch (IOException | ParseException e) {
logger.error("Unable to get the content of the URL: {}. Cause: {}", url, e.getMessage(), e);
}
logContent(content);
return content;
}
use of org.apache.hc.core5.http.copied.NameValuePair in project datagear by datageartech.
the class HttpDataSet method setHttpEntity.
protected void setHttpEntity(ClassicHttpRequest request, String requestContent) throws Throwable {
if (REQUEST_CONTENT_TYPE_FORM_URLENCODED.equals(this.requestContentType)) {
List<NameValuePair> params = toNameValuePairs(requestContent);
if (params == NOT_NAME_VALUE_PAIR_OBJ_ARRAY_JSON)
throw new RequestContentNotNameValueObjArrayJsonException(requestContent);
request.setEntity(new UrlEncodedFormEntity(params, Charset.forName(this.requestContentCharset)));
} else if (REQUEST_CONTENT_TYPE_JSON.equals(this.requestContentType)) {
ContentType contentType = ContentType.create(ContentType.APPLICATION_JSON.getMimeType(), Charset.forName(this.requestContentCharset));
StringEntity entity = new StringEntity(requestContent, contentType);
request.setEntity(entity);
} else
throw new DataSetException("Request content type [" + this.requestContentType + "] is not supported");
}
use of org.apache.hc.core5.http.copied.NameValuePair in project ajapaik-android-app by Ajapaik.
the class WebOperation method performRequest.
public boolean performRequest(String baseURL, Map<String, String> extraParameters, BasicCookieStore cookieStore) {
Log.d(TAG, "performRequest()");
ConnectivityManager cm = (ConnectivityManager) m_context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
boolean isPost = isPost();
String url = m_url;
URI uri;
if (baseURL != null && !url.contains("://")) {
if (url.startsWith("/") && baseURL.endsWith("/")) {
url = baseURL + url.substring(1);
} else {
url = baseURL + url;
}
}
if (m_client == null) {
if (BuildConfig.DEBUG) {
Log.d(TAG, "new m_client");
}
try {
m_client = HttpClients.custom().setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy()).setDefaultCookieStore(cookieStore).build();
} catch (Exception e) {
Log.w(TAG, e.toString());
}
}
if (BuildConfig.DEBUG) {
Log.d(TAG, "m_client ready");
}
m_started = true;
if (info == null || info.getState() == NetworkInfo.State.DISCONNECTED) {
onFailure();
if (BuildConfig.DEBUG) {
Log.d(TAG, "No network connection");
}
return false;
}
try {
uri = URI.create(url);
} catch (Exception e) {
Log.w(TAG, "Unable to parse URL (" + url + ")");
onFailure();
return false;
}
for (int i = 0; i < RETRY_COUNT && !m_cancelled; i++) {
CloseableHttpResponse response = null;
HttpUriRequestBase request;
if (isPost) {
HttpPost postRequest = new HttpPost(uri);
request = postRequest;
if (m_file != null || (extraParameters != null && extraParameters.size() > 0) || (m_parameters != null && m_parameters.size() > 0)) {
List<NameValuePair> postData = new ArrayList<NameValuePair>(((extraParameters != null) ? extraParameters.size() : 0) + ((m_parameters != null) ? m_parameters.size() : 0));
if (m_parameters != null) {
for (Map.Entry<String, String> entry : m_parameters.entrySet()) {
postData.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
if (extraParameters != null) {
for (Map.Entry<String, String> entry : extraParameters.entrySet()) {
postData.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
try {
StringBuilder strData = new StringBuilder();
String separator = "";
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
if (m_file != null) {
Log.d(TAG, "Adding file to post");
for (NameValuePair pair : postData) {
StringBody stringBody1 = new StringBody(pair.getValue(), ContentType.MULTIPART_FORM_DATA);
builder.addPart(pair.getName(), stringBody1);
strData.append(separator);
strData.append(pair.toString());
separator = "&";
}
FileBody fileBody = new FileBody(m_file, ContentType.DEFAULT_BINARY);
builder.addPart("original", fileBody);
HttpEntity entity = builder.build();
postRequest.setEntity(entity);
} else {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postData);
postRequest.setEntity(entity);
for (NameValuePair pair : postData) {
strData.append(separator);
strData.append(pair.toString());
separator = "&";
}
}
if (BuildConfig.DEBUG) {
Log.d(TAG, strData.toString());
}
} catch (Exception e) {
Log.d(TAG, "UTF8 is not supported");
}
}
} else if ((extraParameters != null && extraParameters.size() > 0) || (m_parameters != null && m_parameters.size() > 0)) {
Uri.Builder uriBuilder = Uri.parse(m_url).buildUpon();
if (m_parameters != null) {
for (Map.Entry<String, String> entry : m_parameters.entrySet()) {
uriBuilder.appendQueryParameter(entry.getKey(), entry.getValue());
}
}
if (extraParameters != null) {
for (Map.Entry<String, String> entry : extraParameters.entrySet()) {
uriBuilder.appendQueryParameter(entry.getKey(), entry.getValue());
}
}
request = new HttpGet(URI.create(uriBuilder.build().toString()));
} else {
request = new HttpGet(uri);
}
request.setHeader("Accept-Encoding", CONTENT_ENCODING_GZIP);
try {
String encoding = null;
HttpEntity entity;
if (BuildConfig.DEBUG) {
Log.e(TAG, "Retry count:" + i);
Log.e(TAG, ((isPost) ? "POST: " : "GET: ") + request.toString());
Log.e(TAG, "Cookies before: " + cookieStore.getCookies().toString());
}
response = m_client.execute(request);
if ((entity = response.getEntity()) != null) {
encoding = entity.getContentEncoding();
}
try {
onResponse(response.getCode(), (encoding != null && CONTENT_ENCODING_GZIP.equals(encoding)) ? new GZIPInputStream(entity.getContent()) : entity.getContent());
Log.e(TAG, "responseCode: " + response.getCode());
Log.e(TAG, "Cookies after: " + cookieStore.getCookies().toString());
List<Cookie> cookies = cookieStore.getCookies();
String session_id = null;
for (int n = 0; n < cookies.size(); n++) {
if (cookies.get(n).getName().equals("sessionid")) {
Log.d(TAG, "Cookie :" + cookies.get(n).getName() + "; value " + cookies.get(n).getValue());
session_id = cookies.get(n).getValue();
}
}
// If no session_id in response then kill login
if (session_id == null) {
Log.e(TAG, "No session_id in response cookie");
m_settings.setSession(null);
}
} catch (ApiException e) {
Crashlytics.log(e.toString());
Crashlytics.setString("URL", url);
if (m_parameters != null && !m_parameters.isEmpty()) {
Crashlytics.setString("params", new JSONObject(m_parameters).toString());
}
Crashlytics.logException(e);
}
response.close();
return true;
} catch (IOException e) {
if (BuildConfig.DEBUG) {
Log.w(TAG, "Network error", e);
}
Crashlytics.log(e.toString());
Crashlytics.setString("URL", url);
Crashlytics.logException(e);
try {
HttpEntity entity = response.getEntity();
entity.getContent().close();
} catch (Exception e1) {
}
request.abort();
try {
Thread.sleep(RETRY_INTERVAL);
} catch (InterruptedException e1) {
}
}
}
return true;
}
Aggregations