[Java] 자바 API Key 인증 방식 모듈 및 호출방법
gson 객체 생성시 사용할 DateSerializer
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
public class GsonDateConverterUtil implements JsonSerializer<Date>, JsonDeserializer<Date>{
private static final String FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
try {
return json == null ? null : simpleDateFormat.parse(json.getAsString());
} catch (ParseException e) {
throw new JsonParseException(e);
}
}
public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(FORMAT);
return src == null ? null : new JsonPrimitive(simpleDateFormat.format(src));
}
}
Api 모듈
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
public class ApiUtil {
public static String RestCall (String paramUrl,String url, String key){
try {
String preUrl = "http://xxx.xxx.xxx.xxx:xxxx";
URL apiUrl = new URL(preUrl + url);
HttpURLConnection conn = (HttpURLConnection)apiUrl.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("api_key", key);
conn.setRequestProperty("X-Data-Type", "application/json");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream(),"UTF-8");
osw.write(paramUrl);
osw.flush();
osw.close();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
if (conn.getResponseCode() != 200) {
System.out.println("Failed: HTTP error code : " + conn.getResponseCode());
throw new RuntimeException("Failed: HTTP error code : " + conn.getResponseCode());
} else {
System.out.println("발송 성공");
}
String rtnStr = null;
String line = null;
while((line = br.readLine()) != null){
rtnStr = line;
System.out.println(line);
}
br.close();
conn.disconnect();
return rtnStr;
} catch (IOException e) {
System.out.println("RestCall Fail : " + e.getMessage());
return null;
}
}
}
사용법
HashMap<String, Object> apiMap = new HashMap();
apiMap.put("test1", "111");
apiMap.put("test2", "222");
apiMap.put("vo1", vo1);
// gson 객체 생성
Gson gson = new GsonBuilder().serializeNulls().setPrettyPrinting().registerTypeAdapter(Date.class, new GsonDateConverterUtil()).create();
// Map 데이터를 jsonString으로 변환
String jsonString = gson.toJson(apiMap);
// 호출
String rtnMsg = ApiUtil.RestCall(jsonString,"/api/xxx/xxx/xxx/xxx/xxx","인증키");
// 응답받은 String 형태의 결과값을 Map으로 변환
Map<String, Object> apiResultMap = new HashMap<String, Object>();
apiResultMap = gson.fromJson(rtnMsg, Map.class);
// Map에서 데이터를 꺼낼 때 예
String code = apiResultMap.get("code").toString();
String data = ((Map<String, Object>)apiResultMap.get("returnData")).get("data").toString();
최근댓글