Commit 491db88f authored by Deepak Prabhakar's avatar Deepak Prabhakar

Made JSONFetcher fetch json via POST

parent 3fa94faf
......@@ -3,10 +3,18 @@ package com.postcode.io.json;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.zip.GZIPInputStream;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
......@@ -23,6 +31,8 @@ public class JsonFetcher {
private static final Logger LOGGER = LoggerFactory.getLogger(JsonFetcher.class);
/**
* Pass {@link URL} to get {@link JSONObject} from it
*
* @param urlString
* @return
*/
......@@ -58,4 +68,58 @@ public class JsonFetcher {
return new JSONObject("");
}
}
/**
* Gets {@link JSONObject} from given {@link URL} & {@link JSONObject} via POST
*
* @param url
* @param jsonObject
* @return
* @throws IOException
* @throws Exception
*/
public static JSONObject postURLToJson(URL url, JSONObject jsonObject) throws IOException {
StringEntity input = null;
HttpPost postRequest = null;
CloseableHttpClient httpClient = null;
HttpResponse response = null;
BufferedReader br = null;
StringBuilder sb = null;
try {
LOGGER.info("Create POST Input");
input = new StringEntity(jsonObject.toString());
input.setContentType("application/json;charset=UTF-8");
input.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
LOGGER.info("Creating POST Request");
postRequest = new HttpPost(url.toString());
postRequest.setEntity(input);
postRequest.setHeader("Accept", "application/json");
postRequest.setEntity(input);
LOGGER.info("Creating HTTPClient");
httpClient = HttpClientBuilder.create().build();
LOGGER.info("Executing PostRequest");
response = httpClient.execute(postRequest);
LOGGER.info("creating BufferedReader");
br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
String output;
sb = new StringBuilder();
while ((output = br.readLine()) != null) {
LOGGER.info("Appending JSON to String Builder");
sb.append(output);
}
LOGGER.info("Closing HTTP Connection");
httpClient.close();
} catch (MalformedURLException e) {
LOGGER.info("URL is Malformed {}", e);
throw new MalformedURLException(e.toString());
} catch (IOException e) {
LOGGER.info("Error while reading JSON from URL", e);
throw new IOException(e.toString());
}
if (sb != null) {
return new JSONObject(sb.toString());
} else {
return new JSONObject("");
}
}
}
......@@ -7,9 +7,13 @@ import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
/**
* @author Deepak
*
......@@ -17,9 +21,17 @@ import org.junit.Test;
public class JsonFetcherTest {
@Test
public void testByURL() throws MalformedURLException {
public void testByURL() throws MalformedURLException, UnirestException {
JSONObject json = JsonFetcher.urlToJson(new URL("http://api.postcodes.io/postcodes/bs347np"));
test(json);
Unirest.post("http://api.postcodes.io/postcodes").header("accept", "application/json")
.queryString("postcodes", new String[] { "BS34 7NP" }).field("postcodes", new String[] { "BS34 7NP" })
.asJson();
assertTrue(json.has("status"));
assertTrue(json.has("result"));
test(json.getJSONObject("result"));
Unirest.post("http://api.postcodes.io/postcodes").header("accept", "application/json")
.field("postcodes", "OX49 5NU").field("postcodes", "BS34 7NP").asJson().getBody().getObject();
}
@Test
......@@ -27,13 +39,12 @@ public class JsonFetcherTest {
JSONObject json = JsonFetcher
.urlToJson(new File(System.getProperty("user.dir").concat("/src/test/resources/postcodeLookup.json"))
.toURI().toURL());
test(json);
}
public void test(JSONObject json) {
assertTrue(json.has("status"));
assertTrue(json.has("result"));
JSONObject result = json.getJSONObject("result");
test(json.getJSONObject("result"));
}
public void test(JSONObject result) {
assertEquals("BS34 7NP", (result.getString("postcode")));
assertEquals(1, (result.getInt("quality")));
assertEquals(360605, (result.getInt("eastings")));
......@@ -66,4 +77,22 @@ public class JsonFetcherTest {
assertEquals("UKK12", (codes.getString("nuts")));
}
@Test
public void testPostURLToJson() throws Exception {
JSONObject jsonO = new JSONObject();
JSONArray ja = new JSONArray();
ja.put("BS34 7NP");
ja.put("ST4 2EU");
jsonO.put("postcodes", ja);
String url = "http://api.postcodes.io/postcodes/";
JSONObject json = JsonFetcher.postURLToJson(new URL(url), jsonO);
assertEquals(200, json.getInt("status"));
JSONArray jsonArray = json.getJSONArray("result");
if (jsonArray.getJSONObject(0).getJSONObject("result").getString("postcode").equals("BS34 7NP")) {
test(jsonArray.getJSONObject(0).getJSONObject("result"));
} else {
test(jsonArray.getJSONObject(1).getJSONObject("result"));
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment