일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
Tags
- matplotlib
- Kafka
- analyzer test
- licence delete curl
- MySQL
- zip 암호화
- flask
- 파이썬
- token filter test
- ELASTIC
- Elasticsearch
- Mac
- License
- 900gle
- sort
- zip 파일 암호화
- aggs
- docker
- 차트
- Java
- TensorFlow
- Test
- plugin
- aggregation
- Python
- API
- query
- springboot
- high level client
- license delete
Archives
- Today
- Total
개발잡부
[java] HTTP 통신하기 본문
반응형
HTTP 통신으로 API 호출하기
build.gradle
plugins {
id 'org.springframework.boot' version '2.6.2'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}
group = 'com.ldh'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'org.springframework.boot:spring-boot-starter-web'
compileOnly 'org.projectlombok:lombok'
// https://mvnrepository.com/artifact/org.apache.commons/commons-lang3
implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.12.0'
// https://mvnrepository.com/artifact/com.google.code.gson/gson
implementation group: 'com.google.code.gson', name: 'gson', version: '2.8.9'
// https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple
implementation group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1.1'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
test {
useJUnitPlatform()
}
HttpUtils.java
package com.ldh.embed.http;
import com.google.gson.Gson;
import org.json.simple.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
public class HttpUtils {
private static String encoding ="UTF-8";
public HashMap post(String sendUrl , HashMap<String,Object> data , String sendType ) throws Exception {
JSONObject jobj = null;
URL url = new URL(sendUrl);
Gson gson = new Gson();
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
byte[] postDataBytes = null ;
if(sendType.equals("json")) {
conn.setRequestProperty("Content-Type", "application/json");
String strJson = gson.toJson(data);
postDataBytes = strJson.getBytes("UTF-8");
}else {
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
StringBuilder postData = new StringBuilder();
for (HashMap.Entry<String, Object> param : data.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
postDataBytes = postData.toString().getBytes("UTF-8");
}
if(postDataBytes !=null && postDataBytes.length != 0){
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
StringBuffer sf = new StringBuffer();
for (int c; (c = in.read()) >= 0;) sf.append((char)c);
conn.disconnect();
String resStr = sf.toString();
HashMap resMap = new HashMap();
return gson.fromJson(resStr, resMap.getClass() ) ;
}else {
conn.disconnect();
return null;
}
}
public synchronized static String get(String url, Object parameters){
StringBuffer sb = new StringBuffer();
URLConnection con = null;
OutputStreamWriter osw = null;
InputStreamReader isr = null;
// System.out.println("API 호출 : "+url);
int readTimeout = 60000;
int connectionTimeout = 60000;
try{
con = new URL(url).openConnection();
con.setConnectTimeout(readTimeout);
con.setReadTimeout(connectionTimeout);
if(encoding!=null){
con.setRequestProperty("Accept-Charset", encoding);
}
if(parameters!=null){
con.setDoOutput(true);
osw = new OutputStreamWriter(con.getOutputStream());
osw.write(parameters.toString());
osw.flush();
}
isr = new InputStreamReader(con.getInputStream());
BufferedReader br = new BufferedReader(isr);
String tmp = "";
while((tmp=br.readLine())!=null){
sb.append(tmp);
}
}catch(Exception e){
e.printStackTrace();
}finally{
if(osw != null){
try{
osw.close();
}catch(Exception e){
e.printStackTrace();
}
}
if(isr != null){
try{
isr.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
return sb.toString();
}
}
package com.ldh.embed.http;
public class HttpUtilsTest {
public static void main(String[] args) {
String returnValue = HttpUtils.get("http://localhost:5000/vectors/나이키", null);
System.out.println(returnValue);
}
}
확인해보자
GET http://localhost:5000/vectors/나이키
포스트맨에서 이렇게 나오는데
main 메소드 실행 하여 로그 출력
반응형
'JAVA > java' 카테고리의 다른 글
CommandLineRunner (2) | 2022.03.22 |
---|---|
[java] picocli java sample (0) | 2022.03.22 |
[java] HttpUtils (0) | 2022.01.18 |
Json 파일 읽기 - json.simple (0) | 2022.01.11 |
[selenium] 동적생성 웹페이지 크롤링 (0) | 2022.01.07 |
Comments