Created
September 25, 2015 00:09
-
-
Save confile/c52bad81212011b9efd3 to your computer and use it in GitHub Desktop.
HttpURLConnection Test for Redirect URLs between http and https
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.BufferedReader; | |
import java.io.DataOutputStream; | |
import java.io.IOException; | |
import java.io.InputStreamReader; | |
import java.io.UnsupportedEncodingException; | |
import java.net.HttpURLConnection; | |
import java.net.MalformedURLException; | |
import java.net.ProtocolException; | |
import java.net.URL; | |
import java.net.URLEncoder; | |
import java.nio.charset.Charset; | |
import java.util.Map; | |
import java.util.logging.Logger; | |
public class TestConnectionImpl { | |
private static final String CHARSET = "UTF-8"; | |
private final Logger logger; | |
public TestConnectionImpl() { | |
logger = Logger.getLogger(ParameterConfig.LOGGER_MAJESTELLA_NAME); | |
} | |
public void request(HTTPMethod method, String url, Map<String, String> queryParams, ConnectionCallback callback) { | |
request(method, url, queryParams, "", callback); | |
} | |
public void request(HTTPMethod method, String url, Map<String, String> queryParams, String bodyString, | |
final ConnectionCallback callback) { | |
String queryString = ""; | |
try { | |
queryString = getQueryString(queryParams); | |
} | |
catch(UnsupportedEncodingException e) { | |
logger.severe("ConnectionImpl - request(): UnsupportedEncodingException e: "+e.getMessage()); | |
} | |
URL urlObj = null; | |
try { | |
urlObj = new URL(url + "?" + queryString); | |
} catch (MalformedURLException e) { | |
logger.severe("ConnectionImpl - request(): MalformedURLException e: "+e.getMessage()); | |
e.printStackTrace(); | |
} | |
try { | |
HttpURLConnection connection = (HttpURLConnection)urlObj.openConnection(); | |
connection = addRequestProperties(connection, method); | |
connection = writeToConnection(connection, bodyString); | |
int responseCode = connection.getResponseCode(); | |
if (responseCode != HttpURLConnection.HTTP_OK) { | |
switch(responseCode){ | |
case HttpURLConnection.HTTP_MOVED_TEMP: | |
case HttpURLConnection.HTTP_MOVED_PERM: | |
case HttpURLConnection.HTTP_SEE_OTHER: | |
String newUrl = connection.getHeaderField("Location"); // find the redirect url from "location" header field | |
connection = (HttpURLConnection) new URL(newUrl).openConnection(); //create a new connection on redirect URL | |
connection = addRequestProperties(connection, method); | |
connection = writeToConnection(connection, bodyString); | |
responseCode = connection.getResponseCode(); | |
default: | |
} | |
} | |
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); | |
StringBuilder sb = new StringBuilder(); | |
String line; | |
while ((line = br.readLine()) != null) { | |
sb.append(line+"\n"); | |
} | |
br.close(); | |
String jsonString = sb.toString(); | |
connection.disconnect(); | |
callback.onResponse(responseCode, jsonString); | |
} | |
catch (ProtocolException e) { | |
logger.severe("ConnectionImpl - request(): ProtocolException: "+e.getMessage()); | |
} | |
catch (Exception e) { | |
logger.severe("ConnectionImpl - request(): Exception: "+e.getMessage()); | |
e.printStackTrace(); | |
} | |
} | |
private HttpURLConnection addRequestProperties(HttpURLConnection connection, HTTPMethod method) throws ProtocolException { | |
connection.setReadTimeout(5000); | |
connection.setInstanceFollowRedirects(true); | |
connection.setDoInput(true); | |
connection.setRequestProperty("Content-Type", "application/json; charset="+CHARSET); | |
connection.setRequestProperty("Accept", "application/json"); | |
if (method == HTTPMethod.GET) { | |
connection.setRequestMethod("GET"); | |
} | |
else if (method == HTTPMethod.POST) { | |
connection.setRequestMethod("POST"); | |
connection.setDoOutput(true); // Triggers POST. | |
} | |
else if (method == HTTPMethod.DELETE) { | |
connection.setRequestMethod("DELETE"); | |
} | |
else if (method == HTTPMethod.PUT) { | |
connection.setRequestMethod("PUT"); | |
} | |
else { | |
throw new IllegalStateException("request method undefined: "+method); | |
} | |
return connection; | |
} | |
private HttpURLConnection writeToConnection(HttpURLConnection connection, String bodyString) { | |
if (bodyString.length() > 0) { | |
byte[] postData = bodyString.getBytes(Charset.forName(CHARSET)); | |
int postDataLength = postData.length; | |
connection.setRequestProperty( "Content-Length", Integer.toString( postDataLength )); | |
try { | |
DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); | |
wr.write(postData); | |
} | |
catch(IOException ex) { | |
logger.severe("ConnectionImpl - request(): IOException e: "+ex.getMessage()); | |
ex.printStackTrace(); | |
} | |
} | |
else { | |
try { | |
connection.connect(); | |
} catch (IOException e) { | |
logger.severe("ConnectionImpl - request(): IOException e: "+e.getMessage()); | |
e.printStackTrace(); | |
} | |
} | |
return connection; | |
} | |
private String getQueryString(Map<String, String> params) throws UnsupportedEncodingException { | |
String result = ""; | |
for(Map.Entry<String, String> entry : params.entrySet()) { | |
result += entry.getKey()+"="+ URLEncoder.encode(entry.getValue() == null ? "" : entry.getValue(), CHARSET) + "&"; | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment