[JAVA](Swing) 입력 받고 HTTP 요청 보내기 (GET, POST)
- 문자열 입력받기
- 메이븐 추가 + jackson 추가 (IntelliJ)
- HTTP 요청 (HttpURLConnection)
Java Swing을 이용해 문자열을 입력 받고 해당 문자열을 HTTP 요청 보내는 과정을 설명하겠습니다.
1. 문자열 입력받기
300 * 150 크기의 프레임을 만들고 JTextField, JButton을 추가했습니다.
버튼을 클릭하면 입력한 내용이 출력되도록 작성하였습니다.
JTextField에 "test"를 입력했습니다.
전송 버튼을 누르면 정삭적으로 출력이 됩니다.
코드
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SwingHttpRequest extends JFrame {
JTextField textField = new JTextField(20);
JButton button = new JButton("전송");
public static void main(String[] args) {
SwingHttpRequest swingHttpRequest = new SwingHttpRequest();
swingHttpRequest.sendText();
}
public void sendText() {
add(textField);
add(button);
setVisible(true);
setLayout(new FlowLayout());
setSize(300, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button.addActionListener(new ActionListener() { // 익명 객체
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(textField.getText());
}
});
}
}
2. 메이븐 추가 + jackson 추가 (IntelliJ)
JSON 요청을 보내기 위해 필요한 Jackson 의존성을 추가하기 위해 메이븐을 추가해줬습니다.
(1) Add Framework Support... > Maven 을 추가해줍니다.
(2) 생성된 pom.xml 파일에 아래 코드를 추가해줍니다.
<dependencies>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.2</version>
</dependency>
</dependencies>
적용 후 pom.xml 이미지
3. HTTP 요청 (HttpURLConnection)
HttpURLConnection를 통해 HTTP 요청을 보냈습니다.
요청 보내기
서버 출력 (Spring Boot)
* 한글 & 특수문자 & 공백 전송은 안됩니다. 추가 처리가 필요합니다.
GET 요청
HttpURLConnection connection = null;
.
. 중략
.
// GET
public String sendHttpGetRequest(String targetURL, String jsonValues) throws IOException {
//Create connection
URL url = new URL(targetURL + jsonToQueryString(jsonValues));
// Send request
URLConnection connection = null;
connection = url.openConnection();
connection.setRequestProperty("Accept-Charset", "URF-8");
// Get response
InputStream response = connection.getInputStream();
try (Scanner scanner = new Scanner(response)) {
String responseBody = scanner.useDelimiter("\\A").next();
return responseBody;
}
}
// json(String) => queryString
public String jsonToQueryString(String jsonValues) throws JsonProcessingException {
String queryString = "";
HashMap<String,Object> jsonMap = null;
jsonMap = new ObjectMapper().readValue(jsonValues, HashMap.class);
for(String strKey : jsonMap.keySet()) {
queryString += "?" + strKey + "=" + jsonMap.get(strKey);
}
return queryString;
}
POST 요청
HttpURLConnection connection = null;
.
. 중략
.
// POST
public String sendHttpPostRequest(String targetURL, String jsonValues) {
try {
// Create connection
URL url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json; utf-8");
connection.setRequestProperty("Content-Length", Integer.toString(jsonValues.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoOutput(true);
// Send request
DataOutputStream wr = new DataOutputStream (connection.getOutputStream());
wr.writeBytes(jsonValues);
wr.flush();
wr.close();
// Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
StringBuilder response = new StringBuilder(); // or StringBuffer if Java version 5+
String line;
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
전체 코드
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class SwingHttpRequest extends JFrame {
static HttpURLConnection connection = null;
public static void main(String[] args) throws IOException {
SwingHttpRequest swingHttpRequest = new SwingHttpRequest();
swingHttpRequest.sendText(swingHttpRequest);
}
public void sendText(SwingHttpRequest swingHttpRequest) {
JTextField textField = new JTextField(20);
JButton button = new JButton("GET, POST 요청");
add(textField);
add(button);
setVisible(true);
setLayout(new FlowLayout());
setSize(300, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button.addActionListener(new ActionListener() { // 익명 객체
@Override
public void actionPerformed(ActionEvent e) {
Map<String, String> mapValues = new HashMap<>();
mapValues.put("value", textField.getText());
try {
String jsonValues = new ObjectMapper().writeValueAsString(mapValues);
String getUrl = "http://localhost:8080/get";
String postUrl = "http://localhost:8080/post";
// GET 요청
String getResponse = swingHttpRequest.sendHttpGetRequest(getUrl, jsonValues);
System.out.println("getResponse : " + getResponse);
// POST 요청
String postResponse = swingHttpRequest.sendHttpPostRequest(postUrl, jsonValues);
System.out.println("postResponse : " + postResponse);
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
// POST
public String sendHttpPostRequest(String targetURL, String jsonValues) {
try {
// Create connection
URL url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json; utf-8");
connection.setRequestProperty("Content-Length", Integer.toString(jsonValues.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoOutput(true);
// Send request
DataOutputStream wr = new DataOutputStream (connection.getOutputStream());
wr.writeBytes(jsonValues);
wr.flush();
wr.close();
// Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
StringBuilder response = new StringBuilder(); // or StringBuffer if Java version 5+
String line;
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
// GET
public String sendHttpGetRequest(String targetURL, String jsonValues) throws IOException {
//Create connection
URL url = new URL(targetURL + jsonToQueryString(jsonValues));
// Send request
URLConnection connection = null;
connection = url.openConnection();
connection.setRequestProperty("Accept-Charset", "URF-8");
// Get response
InputStream response = connection.getInputStream();
try (Scanner scanner = new Scanner(response)) {
String responseBody = scanner.useDelimiter("\\A").next();
return responseBody;
}
}
// json(String) => queryString
public String jsonToQueryString(String jsonValues) throws JsonProcessingException {
String queryString = "";
HashMap<String,Object> jsonMap = null;
jsonMap = new ObjectMapper().readValue(jsonValues, HashMap.class);
for(String strKey : jsonMap.keySet()) {
queryString += "?" + strKey + "=" + jsonMap.get(strKey);
}
return queryString;
}
}
서버 코드 (TestController)
import com.testserver.ValueVo;
import org.springframework.web.bind.annotation.*;
@RestController
public class TestController {
@GetMapping("/get")
public String getTest(@RequestParam String value) {
System.out.println("get : " + value);
return value;
}
@PostMapping("/post")
public String postTest(@RequestBody ValueVo valueVo) {
String value = valueVo.getValue();
System.out.println("post : " + value);
return value;
}
}
서버 코드 (ValueVO)
import lombok.Data;
@Data
public class ValueVo {
private String value;
}
참고 링크
https://stackoverflow.com/questions/1359689/how-to-send-http-request-in-java
Author And Source
이 문제에 관하여([JAVA](Swing) 입력 받고 HTTP 요청 보내기 (GET, POST)), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@kkj53051000/JAVASwing-입력-받고-HTTP-요청-보내기-GET-POST저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)