Merge pull request #79 from Doha2012/master

syntax upgrade httpClient
This commit is contained in:
Eugen 2014-11-25 15:22:24 +02:00
commit 3899aa3a92
2 changed files with 179 additions and 184 deletions

View File

@ -15,9 +15,7 @@ import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -27,135 +25,132 @@ import com.google.common.collect.Lists;
public class HttpClientUnshortenLiveTest { public class HttpClientUnshortenLiveTest {
private CloseableHttpClient client; private CloseableHttpClient client;
// fixtures // fixtures
@Before @Before
public final void before() { public final void before() {
final HttpParams httpParameters = new BasicHttpParams(); client = HttpClientBuilder.create().disableRedirectHandling().build();
httpParameters.setParameter("http.protocol.handle-redirects", false); }
client = new DefaultHttpClient(httpParameters); // tests
}
// tests @Test
public final void givenShortenedOnce_whenUrlIsUnshortened_thenCorrectResult() throws IOException {
final String expectedResult = "http://www.baeldung.com/rest-versioning";
final String actualResult = expandSingleLevel("http://bit.ly/13jEoS1");
assertThat(actualResult, equalTo(expectedResult));
}
@Test @Test
public final void givenShortenedOnce_whenUrlIsUnshortened_thenCorrectResult() throws IOException { public final void givenShortenedMultiple_whenUrlIsUnshortened_thenCorrectResult() throws IOException {
final String expectedResult = "http://www.baeldung.com/rest-versioning"; final String expectedResult = "http://www.baeldung.com/rest-versioning";
final String actualResult = expandSingleLevel("http://bit.ly/13jEoS1"); final String actualResult = expand("http://t.co/e4rDDbnzmk");
assertThat(actualResult, equalTo(expectedResult)); assertThat(actualResult, equalTo(expectedResult));
} }
@Test // API
public final void givenShortenedMultiple_whenUrlIsUnshortened_thenCorrectResult() throws IOException {
final String expectedResult = "http://www.baeldung.com/rest-versioning";
final String actualResult = expand("http://t.co/e4rDDbnzmk");
assertThat(actualResult, equalTo(expectedResult));
}
// API final String expand(final String urlArg) throws IOException {
String originalUrl = urlArg;
String newUrl = expandSingleLevel(originalUrl);
while (!originalUrl.equals(newUrl)) {
originalUrl = newUrl;
newUrl = expandSingleLevel(originalUrl);
}
final String expand(final String urlArg) throws IOException { return newUrl;
String originalUrl = urlArg; }
String newUrl = expandSingleLevel(originalUrl);
while (!originalUrl.equals(newUrl)) {
originalUrl = newUrl;
newUrl = expandSingleLevel(originalUrl);
}
return newUrl; final String expandSafe(final String urlArg) throws IOException {
} String originalUrl = urlArg;
String newUrl = expandSingleLevelSafe(originalUrl).getRight();
final List<String> alreadyVisited = Lists.newArrayList(originalUrl, newUrl);
while (!originalUrl.equals(newUrl)) {
originalUrl = newUrl;
final Pair<Integer, String> statusAndUrl = expandSingleLevelSafe(originalUrl);
newUrl = statusAndUrl.getRight();
final boolean isRedirect = statusAndUrl.getLeft() == 301 || statusAndUrl.getLeft() == 302;
if (isRedirect && alreadyVisited.contains(newUrl)) {
throw new IllegalStateException("Likely a redirect loop");
}
alreadyVisited.add(newUrl);
}
final String expandSafe(final String urlArg) throws IOException { return newUrl;
String originalUrl = urlArg; }
String newUrl = expandSingleLevelSafe(originalUrl).getRight();
final List<String> alreadyVisited = Lists.newArrayList(originalUrl, newUrl);
while (!originalUrl.equals(newUrl)) {
originalUrl = newUrl;
final Pair<Integer, String> statusAndUrl = expandSingleLevelSafe(originalUrl);
newUrl = statusAndUrl.getRight();
final boolean isRedirect = statusAndUrl.getLeft() == 301 || statusAndUrl.getLeft() == 302;
if (isRedirect && alreadyVisited.contains(newUrl)) {
throw new IllegalStateException("Likely a redirect loop");
}
alreadyVisited.add(newUrl);
}
return newUrl; final Pair<Integer, String> expandSingleLevelSafe(final String url) throws IOException {
} HttpGet request = null;
HttpEntity httpEntity = null;
InputStream entityContentStream = null;
final Pair<Integer, String> expandSingleLevelSafe(final String url) throws IOException { try {
HttpGet request = null; request = new HttpGet(url);
HttpEntity httpEntity = null; final HttpResponse httpResponse = client.execute(request);
InputStream entityContentStream = null;
try { httpEntity = httpResponse.getEntity();
request = new HttpGet(url); entityContentStream = httpEntity.getContent();
final HttpResponse httpResponse = client.execute(request);
httpEntity = httpResponse.getEntity(); final int statusCode = httpResponse.getStatusLine().getStatusCode();
entityContentStream = httpEntity.getContent(); if (statusCode != 301 && statusCode != 302) {
return new ImmutablePair<Integer, String>(statusCode, url);
}
final Header[] headers = httpResponse.getHeaders(HttpHeaders.LOCATION);
Preconditions.checkState(headers.length == 1);
final String newUrl = headers[0].getValue();
final int statusCode = httpResponse.getStatusLine().getStatusCode(); return new ImmutablePair<Integer, String>(statusCode, newUrl);
if (statusCode != 301 && statusCode != 302) { } catch (final IllegalArgumentException uriEx) {
return new ImmutablePair<Integer, String>(statusCode, url); return new ImmutablePair<Integer, String>(500, url);
} } finally {
final Header[] headers = httpResponse.getHeaders(HttpHeaders.LOCATION); if (request != null) {
Preconditions.checkState(headers.length == 1); request.releaseConnection();
final String newUrl = headers[0].getValue(); }
if (entityContentStream != null) {
entityContentStream.close();
}
if (httpEntity != null) {
EntityUtils.consume(httpEntity);
}
}
}
return new ImmutablePair<Integer, String>(statusCode, newUrl); final String expandSingleLevel(final String url) throws IOException {
} catch (final IllegalArgumentException uriEx) { HttpGet request = null;
return new ImmutablePair<Integer, String>(500, url); HttpEntity httpEntity = null;
} finally { InputStream entityContentStream = null;
if (request != null) {
request.releaseConnection();
}
if (entityContentStream != null) {
entityContentStream.close();
}
if (httpEntity != null) {
EntityUtils.consume(httpEntity);
}
}
}
final String expandSingleLevel(final String url) throws IOException { try {
HttpGet request = null; request = new HttpGet(url);
HttpEntity httpEntity = null; final HttpResponse httpResponse = client.execute(request);
InputStream entityContentStream = null;
try { httpEntity = httpResponse.getEntity();
request = new HttpGet(url); entityContentStream = httpEntity.getContent();
final HttpResponse httpResponse = client.execute(request);
httpEntity = httpResponse.getEntity(); final int statusCode = httpResponse.getStatusLine().getStatusCode();
entityContentStream = httpEntity.getContent(); if (statusCode != 301 && statusCode != 302) {
return url;
}
final Header[] headers = httpResponse.getHeaders(HttpHeaders.LOCATION);
Preconditions.checkState(headers.length == 1);
final String newUrl = headers[0].getValue();
final int statusCode = httpResponse.getStatusLine().getStatusCode(); return newUrl;
if (statusCode != 301 && statusCode != 302) { } catch (final IllegalArgumentException uriEx) {
return url; return url;
} } finally {
final Header[] headers = httpResponse.getHeaders(HttpHeaders.LOCATION); if (request != null) {
Preconditions.checkState(headers.length == 1); request.releaseConnection();
final String newUrl = headers[0].getValue(); }
if (entityContentStream != null) {
return newUrl; entityContentStream.close();
} catch (final IllegalArgumentException uriEx) { }
return url; if (httpEntity != null) {
} finally { EntityUtils.consume(httpEntity);
if (request != null) { }
request.releaseConnection(); }
} }
if (entityContentStream != null) {
entityContentStream.close();
}
if (httpEntity != null) {
EntityUtils.consume(httpEntity);
}
}
}
} }

View File

@ -8,12 +8,12 @@ import java.io.InputStream;
import org.apache.http.HttpEntity; import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.cookie.BasicClientCookie; import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.BasicHttpContext;
@ -24,95 +24,95 @@ import org.junit.Test;
public class HttpClientCookieLiveTest { public class HttpClientCookieLiveTest {
private CloseableHttpClient instance; private CloseableHttpClient instance;
private CloseableHttpResponse response; private CloseableHttpResponse response;
@Before @Before
public final void before() { public final void before() {
instance = HttpClientBuilder.create().build(); instance = HttpClientBuilder.create().build();
} }
@After @After
public final void after() throws IllegalStateException, IOException { public final void after() throws IllegalStateException, IOException {
if (response == null) { if (response == null) {
return; return;
} }
try { try {
final HttpEntity entity = response.getEntity(); final HttpEntity entity = response.getEntity();
if (entity != null) { if (entity != null) {
final InputStream instream = entity.getContent(); final InputStream instream = entity.getContent();
instream.close(); instream.close();
} }
} finally { } finally {
response.close(); response.close();
} }
} }
// tests // tests
@Test @Test
public final void whenSettingCookiesOnARequest_thenCorrect() throws ClientProtocolException, IOException { public final void whenSettingCookiesOnARequest_thenCorrect() throws ClientProtocolException, IOException {
instance = HttpClientBuilder.create().build(); instance = HttpClientBuilder.create().build();
final HttpGet request = new HttpGet("http://www.github.com"); final HttpGet request = new HttpGet("http://www.github.com");
request.setHeader("Cookie", "JSESSIONID=1234"); request.setHeader("Cookie", "JSESSIONID=1234");
response = instance.execute(request); response = instance.execute(request);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
} }
@Test @Test
public final void givenUsingDeprecatedApi_whenSettingCookiesOnTheHttpClient_thenCorrect() throws ClientProtocolException, IOException { public final void givenUsingDeprecatedApi_whenSettingCookiesOnTheHttpClient_thenCorrect() throws ClientProtocolException, IOException {
final BasicCookieStore cookieStore = new BasicCookieStore(); final BasicCookieStore cookieStore = new BasicCookieStore();
final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234"); final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
cookie.setDomain(".github.com"); cookie.setDomain(".github.com");
cookie.setPath("/"); cookie.setPath("/");
cookieStore.addCookie(cookie); cookieStore.addCookie(cookie);
final DefaultHttpClient client = new DefaultHttpClient(); final HttpClient client = HttpClientBuilder.create()
client.setCookieStore(cookieStore); .setDefaultCookieStore(cookieStore).build();
final HttpGet request = new HttpGet("http://www.github.com"); final HttpGet request = new HttpGet("http://www.github.com");
response = client.execute(request); response = (CloseableHttpResponse) client.execute(request);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
} }
@Test @Test
public final void whenSettingCookiesOnTheHttpClient_thenCookieSentCorrectly() throws ClientProtocolException, IOException { public final void whenSettingCookiesOnTheHttpClient_thenCookieSentCorrectly() throws ClientProtocolException, IOException {
final BasicCookieStore cookieStore = new BasicCookieStore(); final BasicCookieStore cookieStore = new BasicCookieStore();
final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234"); final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
cookie.setDomain(".github.com"); cookie.setDomain(".github.com");
cookie.setPath("/"); cookie.setPath("/");
cookieStore.addCookie(cookie); cookieStore.addCookie(cookie);
instance = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build(); instance = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();
final HttpGet request = new HttpGet("http://www.github.com"); final HttpGet request = new HttpGet("http://www.github.com");
response = instance.execute(request); response = instance.execute(request);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
} }
@Test @Test
public final void whenSettingCookiesOnTheRequest_thenCookieSentCorrectly() throws ClientProtocolException, IOException { public final void whenSettingCookiesOnTheRequest_thenCookieSentCorrectly() throws ClientProtocolException, IOException {
final BasicCookieStore cookieStore = new BasicCookieStore(); final BasicCookieStore cookieStore = new BasicCookieStore();
final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234"); final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
cookie.setDomain(".github.com"); cookie.setDomain(".github.com");
cookie.setPath("/"); cookie.setPath("/");
cookieStore.addCookie(cookie); cookieStore.addCookie(cookie);
instance = HttpClientBuilder.create().build(); instance = HttpClientBuilder.create().build();
final HttpGet request = new HttpGet("http://www.github.com"); final HttpGet request = new HttpGet("http://www.github.com");
final HttpContext localContext = new BasicHttpContext(); final HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore); localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
// localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); // before 4.3 // localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); // before 4.3
response = instance.execute(request, localContext); response = instance.execute(request, localContext);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
} }
} }