com.unzer.payment.communication.impl.HttpClientBasedHttpRequest Maven / Gradle / Ivy
package com.unzer.payment.communication.impl;
import com.unzer.payment.communication.UnzerHttpRequest;
import lombok.Getter;
import org.apache.hc.client5.http.classic.methods.*;
import org.apache.hc.core5.http.ClassicHttpRequest;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.io.entity.StringEntity;
import java.net.URI;
import java.net.URISyntaxException;
/**
* Implementation of the {@code UnzerHttpRequest} wrapping an apache
* {@code HttpUriRequest}. Currently supported are:
*
* - GET: mapped by {@code HttpGet}
* - POST: mapped by {@code HttpPost}
* - PUT: mapped by {@code HttpPut}
* - DELETE: mapped by {@code HttpDelete}
*
*/
@Getter
public class HttpClientBasedHttpRequest implements UnzerHttpRequest {
protected ClassicHttpRequest request;
protected UnzerHttpMethod method;
/**
* Creates a {@code HttpClientBasedHttpRequest} wrapping a
* {@code HttpUriRequest} defined by the given {@code UnzerHttpMethod}.
*
* @param uri - the RUI of the request
* @param method - the {@code UnzerHttpMethod} representing one of
* {@code HttpGet}, {@code HttpPost}, {@code HttpPut},
* {@code HttpDelete}
*/
public HttpClientBasedHttpRequest(String uri, UnzerHttpMethod method) {
this.method = method;
request = createRequestForMethod(uri, method);
}
private HttpUriRequest createRequestForMethod(String url, UnzerHttpMethod method) {
switch (method) {
case GET:
return new HttpGet(url);
case POST:
return new HttpPost(url);
case PUT:
return new HttpPut(url);
case DELETE:
return new HttpDelete(url);
case PATCH:
return new HttpPatch(url);
default:
throw new IllegalArgumentException("Unsupported HttpMethod: " + method);
}
}
@Override
public void addHeader(String header, String value) {
this.request.addHeader(header, value);
}
@Override
public URI getURI() throws URISyntaxException {
return request.getUri();
}
@Override
public void setContent(String content, String encoding) {
StringEntity entity = new StringEntity(
content,
ContentType.APPLICATION_JSON,
encoding,
false
);
request.setEntity(entity);
}
@Override
public String toString() {
return this.request.toString();
}
}