전자정부표준프레임워크
api 로 데이타 전송(post)
yeon.Biju
2022. 4. 14. 16:52
api로 데이타를 주고 받는 것의 기본으로 내가 쓰고 있는 방법이다.
POST로 데이타를 주고 받는 것을 정리해봤다.
사실 나는 요청할 데이타를 생성하는 것이 더 헷갈린다.
아래 소스에는 없지만.
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
URL url ;
HttpURLConnection conn;
String resStr = "";
ByteArrayOutputStream baos = null;
int responseCode = 0;
try {
String requestUrl ="https://~~~";
url = new URL(requestUrl);
conn = (HttpURLConnection)url.openConnection();
conn.setConnectTimeout(3000); //3초
conn.setReadTimeout(3000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
//요청데이타 생성
String rqstData =""; //json 형태로 생성
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(rqstData);
wr.flush();
responseCode = conn.getResponseCode();
if(responseCode==200){
InputStream dis = conn.getInputStream();
byte[] bytes = new byte[1024];
baos = new ByteArrayOutputStream();
while(bytes.length > 0){
int red = dis.read(bytes,0,bytes.length);
if(red<0)
break;
baos.write(bytes,0,red);
}
resStr =(baos.toString("UTF-8"));
}
if(baos !=null) {
baos.flush();
}
}catch (MalformedURLException ex) {
ex.printStackTrace();
}catch(IOException ex){
ex.printStackTrace();
}finally {
if (baos != null) try { baos.close(); } catch (IOException ignore) {}
}
|
cs |