Skip to content

Instantly share code, notes, and snippets.

@chrisvoo chrisvoo/fluent.java
Last active Sep 23, 2016

Embed
What would you like to do?
GET/POST HTTP JSON request with Apache Fluent library (libphonenumber Google library)
/**
* Apache HTTP Fluent client configuration
* @throws KeyStoreException
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
* @throws IOException
* @throws CertificateException
*/
public static void httpClientConfigurator() throws KeyStoreException, KeyManagementException, NoSuchAlgorithmException,
CertificateException, IOException {
InputStream instream = null;
HttpsURLConnection.setDefaultHostnameVerifier( new HostnameVerifier(){
@Override
public boolean verify(String string, SSLSession ssls) {
return true;
}
});
keystore = KeyStore.getInstance(KeyStore.getDefaultType());
instream = new KettleMobileTest().getClass()
.getClassLoader()
.getResourceAsStream(keystorePath);
keystore.load(instream, keystorePass.toCharArray());
// Trust own CA and all self-signed certs
SSLContext sslcontext = SSLContexts.custom()
.loadTrustMaterial(keystore, new TrustSelfSignedStrategy())
.build();
// ALLOW_ALL_HOSTNAME_VERIFIER non verifica che il campo CN del certificato
// sia uguale al sito a cui si sta collegando il client, es non fallisce se
// ho CN = localhost ma il client si connette al 172.19.100.95
sslsf = new SSLConnectionSocketFactory(
sslcontext,
new String[] { "TLSv1" },
null,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
}
/**
* <code>
Result: {"numbers": [{"region": "CZ",
"google_ton": 0,
"orig_num": "+420257182666",
"formatted": "+420257182666",
"location": "Prague",
"country_code": 420}]}
</code>
* @throws ClientProtocolException
* @throws IOException
*/
@Test public void libPhoneNumber() throws ClientProtocolException, IOException {
String number = "+420257182666"; // il numero da localizzare
String locale = "IT"; // l'iso code della nazione da cui si fa il numero
String url = "http://URL/phonenumber";
String addOperation = "add00";
List<String> numbers = new ArrayList<String>();
numbers.add(number);
Map<String, Object> params = new HashMap<String, Object>();
params.put("locale", locale);
params.put("numbers", numbers);
params.put("add_operation", addOperation);
String json = new GsonBuilder().serializeNulls().create().toJson(params);
HttpRequestBase req = Utils.postJSON(url, json);
System.out.println("Sending " + json + " to " + url);
try {
PhoneNumberResponse result = Utils.getHttpClient(5, 10).execute(req, new ResponseHandler<PhoneNumberResponse>() {
@Override
public PhoneNumberResponse handleResponse(HttpResponse res) throws ClientProtocolException, IOException {
int httpStatus = res.getStatusLine().getStatusCode();
String reason = res.getStatusLine().getReasonPhrase();
System.out.println(httpStatus + " " + reason);
return new Gson().fromJson(Utils.getJsonFromStream(res), PhoneNumberResponse.class);
}
});
assertEquals("More data than expected!", 1, result.numbers.size());
PhoneNumber pNum = result.numbers.get(0);
assertEquals("region mismatch", "CZ", pNum.region);
assertEquals("google_ton mismatch", 0, pNum.google_ton.intValue());
assertEquals("orig_num mismatch", number, pNum.orig_num);
assertEquals("location mismatch", "Prague", pNum.location);
assertEquals("country_code mismatch", 420, pNum.country_code.intValue());
} catch(HttpHostConnectException conn) {
System.err.println("HttpHostConnectException: " + ExceptionUtils.getStackTrace(conn));
} catch(SocketTimeoutException s) {
System.err.println("SocketTimeoutException: " + ExceptionUtils.getStackTrace(s));
}
}
/* HTTP Utility methods ------------------------------------------- */
public static String getJsonFromStream(HttpResponse res) throws IllegalStateException, IOException {
InputStream is = res.getEntity().getContent();
BufferedReader baff = new BufferedReader(new InputStreamReader(is));
String jsonCode = "", temp = "";
while((temp = baff.readLine()) != null) {
jsonCode += temp;
}
return jsonCode;
}
public static HttpRequestBase postJSON(String url, String json) {
HttpRequestBase baseRequest = new HttpPost(url);
((HttpPost)baseRequest).setEntity(new StringEntity(json, ContentType.create("application/json")));
return baseRequest;
}
/**
* It build an HTTP request
* @param httpMethod it could be GET or POST, otherwise you get NULL
*/
public static HttpRequestBase buildHttpRequestBase(String httpMethod, String url, Map<String, String> params) throws Exception {
HttpRequestBase baseRequest = null;
if(httpMethod.equals("POST")) {
Form form = Form.form();
addParamsToForm(form, params);
baseRequest = new HttpPost(url);
((HttpPost)baseRequest).setEntity(new UrlEncodedFormEntity(form.build()));
} else if(httpMethod.equals("GET")) {
URIBuilder uri = new URIBuilder(url);
addParamsToUri(uri, params);
baseRequest = new HttpGet(uri.build());
}
return baseRequest;
}
/**
* creates a custom HTTP client
* @param connectTimeout timeout in seconds
* @param socketTimeout timeout in seconds
* @return
*/
public static CloseableHttpClient getHttpClient(Integer connectTimeout, Integer socketTimeout) {
// Impostazioni timeout
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(
connectTimeout == null
? 5 * 1000 : connectTimeout * 1000)
.setSocketTimeout(
socketTimeout == null
? 180 * 1000 : socketTimeout * 1000)
.build();
return HttpClients.custom()
.setSSLSocketFactory(sslsf) // see at hte top of this gist
.setDefaultRequestConfig(requestConfig)
.build();
}
/**
* Adds BODY parameters to a HTTP POST request
* @param form
* @param params
*/
private static void addParamsToForm(Form form, Map<String, String> params) {
for(String pName : params.keySet()) {
String val = params.get(pName);
form.add(pName, val);
}
}
/**
* Adds query strings parameters to a HTTP GET request
* @param form
* @param params
*/
private static void addParamsToUri(URIBuilder uri, Map<String, String> params) {
for(String pName : params.keySet()) {
String val = params.get(pName);
uri.addParameter(pName, val);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.