remove utility classes (#1733)

* remove utility classes

* remove httpclient, extend http

* move code to core-java
This commit is contained in:
lor6 2017-04-28 14:37:51 +03:00 committed by KevinGilmore
parent 1c24e0a2cf
commit e83002ce99
8 changed files with 147 additions and 317 deletions

View File

@ -0,0 +1,21 @@
package com.baeldung.http;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
public class ParameterStringBuilder {
public static String getParamsString(Map<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
result.append("&");
}
String resultString = result.toString();
return resultString.length() > 0 ? resultString.substring(0, resultString.length() - 1) : resultString;
}
}

View File

@ -0,0 +1,126 @@
package com.baeldung.http;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import static org.junit.Assert.*;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.CookieManager;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class HttpRequestTest {
@Test
public void whenGetRequest_thenOk() throws IOException {
URL url = new URL("http://example.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
Map<String, String> parameters = new HashMap<>();
parameters.put("param1", "val");
con.setDoOutput(true);
DataOutputStream out = new DataOutputStream(con.getOutputStream());
out.writeBytes(ParameterStringBuilder.getParamsString(parameters));
out.flush();
out.close();
con.setConnectTimeout(5000);
con.setReadTimeout(5000);
int status = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
assertEquals("status code incorrect", status, 200);
assertTrue("content incorrect", content.toString().contains("Example Domain"));
}
@Test
public void whenPostRequest_thenOk() throws IOException {
URL url = new URL("http://example.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
Map<String, String> parameters = new HashMap<>();
parameters.put("param1", "val");
con.setDoOutput(true);
DataOutputStream out = new DataOutputStream(con.getOutputStream());
out.writeBytes(ParameterStringBuilder.getParamsString(parameters));
out.flush();
out.close();
int status = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
assertEquals("status code incorrect", status, 200);
}
@Test
public void whenGetCookies_thenOk() throws IOException {
URL url = new URL("http://example.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
CookieManager cookieManager = new CookieManager();
String cookiesHeader = con.getHeaderField("Set-Cookie");
Optional<HttpCookie> usernameCookie = null;
if (cookiesHeader != null) {
List<HttpCookie> cookies = HttpCookie.parse(cookiesHeader);
cookies.forEach(cookie -> cookieManager.getCookieStore().add(null, cookie));
usernameCookie = cookies.stream().findAny().filter(cookie -> cookie.getName().equals("username"));
}
if (usernameCookie == null) {
cookieManager.getCookieStore().add(null, new HttpCookie("username", "john"));
}
con.disconnect();
con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("Cookie", StringUtils.join(cookieManager.getCookieStore().getCookies(), ";"));
int status = con.getResponseCode();
assertEquals("status code incorrect", status, 200);
}
@Test
public void whenRedirect_thenOk() throws IOException {
URL url = new URL("http://example.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setInstanceFollowRedirects(true);
int status = con.getResponseCode();
if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM) {
String location = con.getHeaderField("Location");
URL newUrl = new URL(location);
con = (HttpURLConnection) newUrl.openConnection();
}
assertEquals("status code incorrect", con.getResponseCode(), 200);
}
}

View File

@ -1,49 +0,0 @@
package com.baeldung.http;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import org.apache.log4j.Logger;
public class HttpRequestBuilder {
private static final Logger LOG = Logger.getLogger(HttpRequestBuilder.class);
public HttpResponseWrapper sendRequest(String urlString, String method, Map<String, String> parameters, Map<String, String> properties) throws IOException{
URL url = new URL(urlString);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod(method);
if (properties != null) {
properties.forEach((key, value) -> con.setRequestProperty(key, value));
}
if (parameters != null) {
con.setDoOutput(true);
DataOutputStream out = new DataOutputStream(con.getOutputStream());
out.writeBytes(ParameterStringBuilder.getParamsString(parameters));
out.flush();
out.close();
}
int status = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
HttpResponseWrapper responseWrapper = new HttpResponseWrapper();
responseWrapper.setStatus(status);
responseWrapper.setContent(content.toString());
return responseWrapper;
}
}

View File

@ -1,31 +0,0 @@
package com.baeldung.http;
public class HttpResponseWrapper {
private int status;
private String content;
public HttpResponseWrapper(){ }
public HttpResponseWrapper(int status, String content) {
super();
this.status = status;
this.content = content;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}

View File

@ -1,27 +0,0 @@
package com.baeldung.http;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
public class ParameterStringBuilder {
public static String getParamsString(Map<String, String> params) {
StringBuilder result = new StringBuilder();
params.forEach((key, value) -> {
try {
result.append(URLEncoder.encode(key, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(value, "UTF-8"));
result.append("&");
} catch (UnsupportedEncodingException exc) {
}
});
String resultString = result.toString();
if (resultString.length() > 0) {
resultString = resultString.substring(0, resultString.length() - 1);
}
return resultString;
}
}

View File

@ -1,124 +0,0 @@
package com.baeldung.httpclient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import com.baeldung.http.HttpResponseWrapper;
import com.baeldung.http.ParameterStringBuilder;
public class HttpClientRequestBuilder {
public HttpResponseWrapper sendGetRequest(String url, Map<String, String> parameters) {
HttpClient client = HttpClientBuilder.create()
.build();
if (parameters != null) {
url += "?" + ParameterStringBuilder.getParamsString(parameters);
}
HttpGet request = new HttpGet(url);
try {
HttpResponse response = client.execute(request);
HttpResponseWrapper responseWrapper = new HttpResponseWrapper();
responseWrapper.setStatus(response.getStatusLine()
.getStatusCode());
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
String line = "", content = "";
while ((line = in.readLine()) != null) {
content += line;
}
responseWrapper.setContent(content);
return responseWrapper;
} catch (ClientProtocolException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public HttpResponseWrapper sendPostRequestWithParameters(String url, Map<String, String> parameters) {
HttpClient client = HttpClientBuilder.create()
.build();
HttpPost request = new HttpPost(url);
try {
if (parameters != null) {
List<NameValuePair> nameValuePairs = new ArrayList<>();
parameters.forEach((key, value) -> nameValuePairs.add(new BasicNameValuePair(key, value)));
request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
}
HttpResponse response = client.execute(request);
HttpResponseWrapper responseWrapper = new HttpResponseWrapper();
responseWrapper.setStatus(response.getStatusLine()
.getStatusCode());
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
String line = "", content = "";
while ((line = in.readLine()) != null) {
content += line;
}
responseWrapper.setContent(content);
return responseWrapper;
} catch (ClientProtocolException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public HttpResponseWrapper sendPostRequestWithJson(String url, String json) {
HttpClient client = HttpClientBuilder.create()
.build();
HttpPost request = new HttpPost(url);
try {
request.addHeader("Content-Type", "application/json");
request.setEntity(new StringEntity(json));
HttpResponse response = client.execute(request);
HttpResponseWrapper responseWrapper = new HttpResponseWrapper();
responseWrapper.setStatus(response.getStatusLine()
.getStatusCode());
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
String line = "", content = "";
while ((line = in.readLine()) != null) {
content += line;
}
responseWrapper.setContent(content);
return responseWrapper;
} catch (ClientProtocolException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}

View File

@ -1,40 +0,0 @@
package com.baeldung.http;
import org.junit.Test;
import static org.junit.Assert.*;
import java.util.HashMap;
import java.util.Map;
import org.junit.Before;
import java.io.IOException;
public class HttpRequestBuilderTest {
private HttpRequestBuilder requestPerformer;
@Before
public void setup() {
requestPerformer = new HttpRequestBuilder();
}
@Test
public void whenGetRequest_thenOk() throws IOException {
HttpResponseWrapper response = requestPerformer.sendRequest("http://www.example.com", "GET", null, null);
assertEquals("status code incorrect", response.getStatus(), 200);
assertTrue("content incorrect", response.getContent()
.contains("Example Domain"));
}
@Test
public void whenPostRequest_thenOk() throws IOException {
Map<String, String> parameters = new HashMap<>();
parameters.put("param1", "val");
Map<String, String> properties = new HashMap<>();
properties.put("Content-Type", "application/json");
HttpResponseWrapper response = requestPerformer.sendRequest("http://www.example.com", "POST", parameters, properties);
assertEquals("status code incorrect", response.getStatus(), 200);
}
}

View File

@ -1,46 +0,0 @@
package com.baeldung.httpclient;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.HashMap;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import com.baeldung.http.HttpResponseWrapper;
public class HttpClientRequestBuilderTest {
private HttpClientRequestBuilder requestBuilder;
@Before
public void setup() {
requestBuilder = new HttpClientRequestBuilder();
}
@Test
public void whenGetRequest_thenOk() {
Map<String, String> parameters = new HashMap<>();
parameters.put("param1", "val");
HttpResponseWrapper response = requestBuilder.sendGetRequest("http://www.example.com",parameters);
assertEquals("status code incorrect", response.getStatus(), 200);
assertTrue("content incorrect", response.getContent()
.contains("Example Domain"));
}
@Test
public void whenPostRequestWithParameters_thenOk() {
Map<String, String> parameters = new HashMap<>();
parameters.put("param1", "val");
HttpResponseWrapper response = requestBuilder.sendPostRequestWithParameters("http://www.example.com", parameters);
assertEquals("status code incorrect", response.getStatus(), 200);
}
@Test
public void whenPostRequestWithJson_thenOk() {
String json = "{\"id\":\"1\"}";
HttpResponseWrapper response = requestBuilder.sendPostRequestWithJson("http://www.example.com",json);
assertEquals("status code incorrect", response.getStatus(), 200);
}
}