App.java
public static void main( String[] args ) {
String baseUrl = "http://httpbin.org/get";
HttpURLConnection con = null;
try {
URL url = new URL(baseUrl);
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setInstanceFollowRedirects(false);
con.connect();
int status = con.getResponseCode();
// HTTPステータスが200の場合、JSONを受け取る
if (status == HttpURLConnection.HTTP_OK) {
try (InputStreamReader in = new InputStreamReader(con.getInputStream());
BufferedReader reader = new BufferedReader(in);) {
StringBuilder output = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
output.append(line);
}
// 一旦、返り値のJSONを確認
System.out.println(output.toString());
ObjectMapper mapper = new ObjectMapper();
// JSONに変換
ResponseBody hoge = mapper.readValue(output.toString(), ResponseBody.class);
// JSONに変換後に試しに出力
System.out.println(hoge.getHeadersData().getHost());
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
con.disconnect();
}
}
ResponseBody.java
public class ResponseBody {
@JsonProperty("args")
private Args args;
@JsonProperty("headers")
private HeadersData headersData;
@JsonProperty("origin")
private String origin;
@JsonProperty("url")
private String url;
}
HeadersData.java
public class HeadersData {
@JsonProperty("Accept")
private String accept;
@JsonProperty("Host")
private String host;
@JsonProperty("User-Agent")
private String userAgent;
@JsonProperty("Content-Type")
private String contentType;
@JsonProperty("X-Amzn-Trace-Id")
private String xAmznTraceId;
}
ResponseBody body = new ResponseBody();
HeadersData headersData = new HeadersData();
Args args = new Args();
body.setArgs(args);
body.setHeadersData(headersData);
headersData.setAccept("text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2");
headersData.setHost("httpbin.org");
headersData.setUserAgent("Java/1.8.0_60");
headersData.setUserAgent("application/json; charset=utf-8");
headersData.setxAmznTraceId("Root=1-64169ad1-3d6687174f0166035a7bea81");
body.setOrigin("122.209.27.26");
body.setUrl("http://httpbin.org/get");
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(body);
System.out.println("出力して確認ーーー");
System.out.println(json);