파일명 MySchedule.java
package com.example.schedule;
import java.io.IOException;
import java.util.Date;
import com.example.repository.ProductCountRepository;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@Component
public class MySchedule {
@Autowired ProductCountRepository pcRepository;
public void printData(){
Date date = new Date();
System.out.println(date.toString());
}
// @Scheduled(cron = "*/10 * * * * *")
public void printData1()throws IOException{
final String URL = "http://ihongss.com/json/exam1.json";
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(URL).build();
Response response = client.newCall(request).execute();
String msg = response.body().string();
// {"ret":"y","data":"123"}
// [{"ret":"y","data":"123"}, {"ret":"y","data":"123"}]
System.out.println(msg);
JSONObject jobj = new JSONObject(msg);
System.out.println(jobj.getString("ret"));
System.out.println(jobj.getInt("data"));
// ProductCountEntity p = new ProductCountEntity();
// pcRepository.save(p);
}
// api 받아오기
// @Scheduled(cron = "*/10 * * * * * ")
public void apiData() throws JSONException, IOException {
final String URL = "http://apis.data.go.kr/6260000/WalkingService/getWalkingKr?serviceKey=JFOZcqivwi%2FGcfzCr%2B0hUL7q99Nnht8YxbkirJXpPJu6M0m81LAIW4WWYjq0wMeT9RlvuN%2FIqMPvhCToNKQ5xA%3D%3D&numOfRows=10&pageNo=1&resultType=json";
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(URL)
.build();
Response response = client.newCall(request).execute();
String msg = response.body().string();
// System.out.println("=== msg === " + msg);
// === msg === {"ret":"y","data":"123"} => String
// JSONObject = {"ret":"y","data":"123"}
// JSONArray = [{"ret":"y","data":"123"}, {"ret":"y","data":"123"}]
// response 데이터를 json으로 파싱
JSONObject json = new JSONObject(msg).getJSONObject("getWalkingKr");
// System.out.println("=== json === " + json);
// System.out.println(json.getJSONArray("item"));
JSONArray array = new JSONArray(json.getJSONArray("item"));
// System.out.println("=== array === " + array);
System.out.println(array.getJSONObject(0));
// System.out.println("=== json.getString('getWalkingKr') === " +
// json.getJSONObject("getWalkingKr"));
// JSONObject getWalkingKr = new JSONObject(json.getJSONObject("getWalkingKr"));
// System.out.println("=== getWalkingKr === " + getWalkingKr);
// System.out.println("=== ret === " + json);
// System.out.println("=== data === " + json.getInt("data"));
}
}