Is there a way, using the below Java code, to convert HashMap into JSON? I have
ID: 3748011 • Letter: I
Question
Is there a way, using the below Java code, to convert HashMap into JSON? I have tried to figure this out but I'm not familiar with using JSON and I don't know how to do it.
//Response Header Imports
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.net.MalformedURLException;
/////////////////////////////////
import org.apache.catalina.Server;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import java.util.HashMap;
import java.util.Map;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import java.security.cert.Certificate;
import javax.net.ssl.SSLPeerUnverifiedException;
import java.net.MalformedURLException;
import java.io.IOException;
public class ServerAnalyzerBackEnd {
private String url;
public ServerAnalyzerBackEnd(String url) {
this.url = url;
}
public ModelAndView start() {
Map<String, Object> params = new HashMap<>();
params.put("url", url);
String secureURL = "";
URL testURL;
//url is not null, assign to secureURL to create https connection
if(url != null){
secureURL = url;
}
//Initialize Strings for later output
String response_header = "";
//create URL object from 'url'
//create https connection based off of url and then call getCertChain method to pull that cert chain
try {
testURL = new URL(secureURL);
HttpsURLConnection connection = (HttpsURLConnection)testURL.openConnection();
getCertChain(connection);
response_header = getResponseHeader(connection);
}
catch(MalformedURLException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
//Put strings into Hash Map to be displayed in output
params.put("response_header", response_header);
return new ModelAndView("showURL", params);
}
public void getCertChain(HttpsURLConnection connection){
if(connection != null){
try{
//this initiates handshake, to ssl server without it, handshake will not occur and 500 error will be thrown
connection.getInputStream();
//make array of Certificate objects and grab the cert chain from the https connection
Certificate[] certificates = connection.getServerCertificates();
//foreach c in Certificates print cert details to console.
for(Certificate c : certificates){
System.out.println("cert type: " + c.getType());
System.out.println("cert PK Algorithm: " + c.getPublicKey().getAlgorithm());
System.out.println("cert PK Format: " + c.getPublicKey().getFormat());
System.out.println();
}
}
catch (SSLPeerUnverifiedException e){
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}
}
}
public String getResponseHeader(HttpsURLConnection connection){
String result = "Key 'Content-Type' is not found!";
//Response Header Function
try {
System.out.println("HTTP Headers");
System.out.println();
Map<String, List<String>> map = connection.getHeaderFields();
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
System.out.println();
System.out.println("Get Header by key:");
String server = connection.getHeaderField("Content-Type");
if (server != null) {
result = "Content-Type: " + server;
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(result);
return result;
}
}
Explanation / Answer
Program:
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.net.MalformedURLException;
import org.json.JSONObject;
import org.springframework.web.servlet.ModelAndView;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import javax.net.ssl.HttpsURLConnection;
import java.security.cert.Certificate;
import javax.net.ssl.SSLPeerUnverifiedException;
public class ServerAnalyzerBackEnd {
private String url;
public ServerAnalyzerBackEnd(String url) {
this.url = url;
}
public ModelAndView start() {
Map<String, Object> params = new HashMap<>();
params.put("url", url);
String secureURL = "";
URL testURL;
//url is not null, assign to secureURL to create https connection
if(url != null){
secureURL = url;
}
//Initialize Strings for later output
String response_header = "";
//create URL object from 'url'
//create https connection based off of url and then call getCertChain method to pull that cert chain
try {
testURL = new URL(secureURL);
HttpsURLConnection connection = (HttpsURLConnection)testURL.openConnection();
getCertChain(connection);
response_header = getResponseHeader(connection);
}
catch(MalformedURLException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
//Put strings into Hash Map to be displayed in output
params.put("response_header", response_header);
//there many ways to return JSON object in that this is one way
ObjectMapper mapperObj = new ObjectMapper();
String json="";
try {
json = mapperObj.writeValueAsString(params);
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Adding View name while creating ModelAndView object
ModelAndView mav=new ModelAndView("showURL");
mav.addObject(json); //Adding an JSON object
return mav;
// return new ModelAndView("showURL",json);
}
public void getCertChain(HttpsURLConnection connection){
if(connection != null){
try{
//this initiates handshake, to ssl server without it, handshake will not occur and 500 error will be thrown
connection.getInputStream();
//make array of Certificate objects and grab the cert chain from the https connection
Certificate[] certificates = connection.getServerCertificates();
//foreach c in Certificates print cert details to console.
for(Certificate c : certificates){
System.out.println("cert type: " + c.getType());
System.out.println("cert PK Algorithm: " + c.getPublicKey().getAlgorithm());
System.out.println("cert PK Format: " + c.getPublicKey().getFormat());
System.out.println();
}
}
catch (SSLPeerUnverifiedException e){
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}
}
}
public String getResponseHeader(HttpsURLConnection connection){
String result = "Key 'Content-Type' is not found!";
//Response Header Function
try {
System.out.println("HTTP Headers");
System.out.println();
Map<String, List<String>> map = connection.getHeaderFields();
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
System.out.println();
System.out.println("Get Header by key:");
String server = connection.getHeaderField("Content-Type");
if (server != null) {
result = "Content-Type: " + server;
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(result);
return result;
}
}
Output:
cert type: X.509
cert PK Algorithm: EC
cert PK Format: X.509
cert type: X.509
cert PK Algorithm: RSA
cert PK Format: X.509
HTTP Headers
Transfer-Encoding: [chunked]
null: [HTTP/1.1 200 OK]
Alt-Svc: [quic=":443"; ma=2592000; v="44,43,39,35"]
Server: [gws]
P3P: [CP="This is not a P3P policy! See g.co/p3phelp for more info."]
Date: [Sat, 15 Sep 2018 21:34:23 GMT]
Accept-Ranges: [none]
X-Frame-Options: [SAMEORIGIN]
Cache-Control: [private, max-age=0]
Vary: [Accept-Encoding]
Set-Cookie: [NID=139=gWqo_-1bPJJvrm2SnY4vVwPd5SI7dKkqcZAuXq8JLOdpMNT6JdkMiqtG3DWk8a02YN2bgB5Dwb5Nee3yYCARH0TI_p6Z4Ecy9_J5E5DIskxXyFHa2osvnKx4cpXZsgY1; expires=Sun, 17-Mar-2019 21:34:23 GMT; path=/; domain=.google.co.in; HttpOnly, 1P_JAR=2018-09-15-21; expires=Mon, 15-Oct-2018 21:34:23 GMT; path=/; domain=.google.co.in]
Expires: [-1]
X-XSS-Protection: [1; mode=block]
Content-Type: [text/html; charset=UTF-8]
Get Header by key:
Content-Type: text/html; charset=UTF-8
Your Model Content AS JSON:
print Model : {string={"response_header":"Content-Type: text/html; charset=UTF-8","url":"https://www.google.co.in/maps/@13.0000588,78.1647889,15z"}}
Here don't mistake "{string=" is added reason is since I have converted Json to String using ObjectMapper and we are returning the Model instead of object, model will always returns an "DataType of an object"(String) & "Value of an object"({"response_header":"Content-Type: text/html; charset=UTF-8","url":"https://www.google.co.in/maps/@13.0000588,78.1647889,15z"}).
print View : showURL
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.