I am attempting to run a simple HTTP server that I will send a request to with JSON string in the body and I need to extract data from it. I'm new to Java and having a difficulty doing so. Ive searched online and most of the examples dont work for me, so there must be something im doing wrong.
public class shareManagerServer {
public static void main(String[] args) throws IOException {
HttpServer server = HttpServer.create(new InetSocketAddress(8500), 0);
HttpContext context = server.createContext("/shareWithUser");
context.setHandler(shareManagerServer::handleshareWithUserRequest);
server.start();
}
private static void handleshareWithUserRequest(HttpExchange exchange) throws IOException {
if (exchange.getRequestMethod().equalsIgnoreCase("POST")) {
Headers requestHeaders = exchange.getRequestHeaders();
// Request body
String body = utils.readString(exchange.getRequestBody());
}
}
}
Based on this, how would I get this to an object that I can access the JSON information with? For testing im sending this curl:
curl -X POST -d "{'age':26,'email':'norman#futurestud.io','isDeveloper':true,'name':'Norman'}" localhost:8500/shareWithUser
Edit:
From my utils:
public class utils {
public static String readString(InputStream inputStream) throws IOException {
ByteArrayOutputStream into = new ByteArrayOutputStream();
byte[] buf = new byte[4096];
for (int n; 0 < (n = inputStream.read(buf));) {
into.write(buf, 0, n);
}
into.close();
return new String(into.toByteArray(), "UTF-8"); // Or whatever encoding
}
}
First you can create class with having all the properties
public class Person {
private int age;
private String email;
private boolean isDeveloper;
private String name;
//getters and setters
}
Now it is pretty string forward by using Gson
String body = utils.readString(exchange.getRequestBody());
Gson gson = new Gson();
Person person = gson.fromJson(body, Person.class);
Related
I am trying to display data from a web service and getting this error :
Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token at...
Find below my code :
Model object :
public class Commune implements Serializable{
private static final long serialVersionUID = 1L;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return "Commune [name=" + name + "]";
}
}
Main class:
public class Test {
public static void main(String[] args) throws IOException {
URL url = new URL("https://bj-decoupage-territorial.herokuapp.com/api/v1/towns");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/json");
if(connection.getResponseCode() != 200){
throw new RuntimeException("Failed : Http code : "+connection.getResponseCode());
}
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String output;
while((output = reader.readLine()) != null){
ObjectMapper mapper = new ObjectMapper();
TypeReference<List<Commune>> mapType = new TypeReference<List<Commune>>() {};
List<Commune> jsonToCommuneList = mapper.readValue(output, mapType);
for(Commune c : jsonToCommuneList) {
System.out.println(c.getName());
}
}
connection.disconnect();
}
}
Here is the data getting from the url :
{"towns":
[
{"name":"BANIKOARA"},
{"name":"GOGOUNOU"},
{"name":"KANDI"},
{"name":"KARIMAMA"}
]
}
Help me please to check what i did wrong.
Thank you
You are getting this error because you are trying to deserialize something that is not actually a JSON Array into a Collection
If you are able to change your JSON to send just a JSON Array format, it will look like this one below:
[
{"name":"BANIKOARA"},
{"name":"GOGOUNOU"},
{"name":"KANDI"},
{"name":"KARIMAMA"}
]
Otherwise, to parse it correctly you also can create a new class which will represent the town of your JSON and parse using it:
public class TownRecords implements Serializable {
private List<Commune> communes;
... getters and setters
}
You're trying to deserialize a list of Commune, but in HTTP response you're getting an object, containing such a list, but not a list itself. So, you need another wrapper object for deserialisation:
Wrapper
public class Towns implements Serializable {
private List<Commune> towns;
public Towns() {}
public List<Commune> getTowns() {
return towns;
}
public void setTowns(List<Commune> towns) {
this.towns = towns;
}
#Override
public String toString() {
return "Towns: " + towns.toString();
}
}
main app
TypeReference<Towns> mapType = new TypeReference<Towns>() {};
Towns towns = mapper.readValue(output, mapType);
System.out.println(towns);
I have the method:
public HTTPResult get(String url) throws Exception{
try {
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
return new HTTPResult(response.getBody(), response.getStatusCode().value());
}
catch (ResourceAccessException e) {
String responseBody = e.getCause().getMessage();
JSONObject obj = new JSONObject(responseBody);
return new HTTPResult(obj.getString("responseBody"), Integer.parseInt(obj.getString("statusCode")));
}
}
I want to do unit testing for it and i am not sure how to proceed:
public class MockHttpServerTest {
private static final int PORT = 51234;
private static final String baseUrl = "http://localhost:" + PORT;
private MockHttpServer server;
private SimpleHttpResponseProvider responseProvider;
private HttpClient client;
#Before
public void setUp() throws Exception {
responseProvider = new SimpleHttpResponseProvider();
server = new MockHttpServer(PORT, responseProvider);
server.start();
client = new DefaultHttpClient();
}
I am getting RED for MockHttpServer & SimpleHttpResponseProvider which should be part of org.apache.wink.client.*; which i am importing. so why do i have red ones? is there some simple way to unit test it?
HTTPResult return me response code and message.
I"m given a requirement on how to test HTTP website without UI. Let says, we have a google website search functionalities (Not Web Services) and I need to test it. How to start? Can anyone give some example (JUnit)(Get/Post Method) for me to start this project. I tried reading the official documentation but found nothing about it. Thanks in advance.
You can do it with the following snippet
public class Searcher {
public String search(String searchUrl, String searchWord) throws IOException, URISyntaxException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
URIBuilder builder = new URIBuilder(searchUrl);
builder.setParameter("search_term", searchWord);
HttpGet request = new HttpGet(builder.build());
HttpResponse httpResponse = httpClient.execute(request);
return convertResponseToString(httpResponse);
}
}
private String convertResponseToString(HttpResponse response) throws IOException {
try (Scanner scanner = new Scanner(response.getEntity().getContent(), "UTF-8")) {
String responseString = scanner.useDelimiter("\\Z").next();
return responseString;
}
}
}
public class SearcherTest {
#Rule
public WireMockRule wireMockRule = new WireMockRule(options().dynamicPort());
#Test
public void searchTest() throws IOException, URISyntaxException {
String searchWord = "something";
String expectedResult = "Your expected result";
stubFor(get(urlPathEqualTo("/search"))
.withQueryParam("search_term", equalTo(searchWord))
.willReturn(aResponse()
.withBody(expectedResult)));
Searcher searcher = new Searcher();
String searchResult = searcher.search("http://localhost:" + wireMockRule.port() + "/search", searchWord);
verify(getRequestedFor(urlPathEqualTo("/search"))
.withQueryParam("search_term", equalTo(searchWord)));
assertEquals(expectedResult, searchResult);
}
}
I would like to use CognitiveJ (GitHub from CognitiveJ) but all I get is:
Status:401; Body: {"error":{"code":"Unspecified","message":"Access denied due to invalid subscription key. Make sure you are subscribed to an API you are trying to call and provide the right key."}}
Here is the Code:
public static String lic1 = "xxx";
public static String lic2 = "xxx";
public static void main(String[] args) throws IOException {
new Bildkontrolle();
}
public Bildkontrolle() throws IOException {
File imageFile = new File("E:\\DSC00306.jpg");
new FaceRecognicion(lic1, lic2, imageFile);
}
And here the second class:
public FaceRecognicion(String lic1, String lic2, File imageFile) throws IOException {
BufferedImage bufImage = ImageIO.read(imageFile);
InputStream inpStream = new FileInputStream(imageFile);
FaceScenarios faceScenarios = new FaceScenarios(lic1,
lic1);
ImageOverlayBuilder imageOverlayBuilder = ImageOverlayBuilder.builder(bufImage);
imageOverlayBuilder.outlineFacesOnImage(faceScenarios.findFaces(inpStream), RectangleType.FULL,
CognitiveJColourPalette.STRAWBERRY).launchViewer();
}
Does anyone have an examplecode where I can look up how to use the API.
I stuck at the point where to send the Request.
it's my first question here, i've try to be the more explicit :)
I want get value from a JSON page : https://api.dailymotion.com/video/x3p6d9r?fields=onair.
I have follow a tutorial about json object.
But i want get the value "onair" and put this in a String for use a IF STRING == "XX".
This is my code :
public class notification extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification);
detectonline();
}
public void detectonline(){
/*
if (xx == "false") {
Do something is live is off
}
else{
Do something is live is on
}
*/
}
public static boolean checkIfOnline(String channel) throws IOException {
String channerUrl = "https://api.dailymotion.com/video/x3p6d9r?fields=onair";
String jsonText = readFromUrl(channerUrl);// reads text from URL
JsonParser parser = new JsonParser();
JsonObject json = parser.parse(jsonText).getAsJsonObject();
return !json.get("onair").isJsonNull();
}
private static String readFromUrl(String url) throws IOException {
URL page = new URL(url);
StringBuilder sb = new StringBuilder();
Scanner scanner = null;
try{
//scanner = new Scanner(page.openStream(), StandardCharsets.UTF_8.name());
scanner = new Scanner(page.openStream());
while (scanner.hasNextLine()){
sb.append(scanner.nextLine());
}
}finally{
if (scanner!=null)
scanner.close();
}
return sb.toString();
}
}
I remake your method according what you are looking for it's one of several way to parse json data :
public static boolean checkIfOnline(String channel) throws JSONException, IOException {
String channerUrl = "https://api.dailymotion.com/video/x3p6d9r?fields=onair";
String jsonText = readFromUrl(channerUrl);// reads text from URL
JSONObject json = new JSONObject(jsonText); // You create a json object from your string jsonText
if(json.has("onair")) { // just a simple test to check the node that you need existe
boolean value = json.getBoolean("onair"); // In the url that you gave onair value is boolean type
return value;
}
return false;
}
I will create methode using your way !
public static boolean checkIfOnline(String channel) throws IOException {
String channerUrl = "https://api.dailymotion.com/video/x3p6d9r?fields=onair";
String jsonText = readFromUrl(channerUrl);// reads text from URL
JsonParser parser = new JsonParser();
String myString =json.get("onair");
return mystring;}