Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

3주차 미션 / 서버 1조 - 강연주 #6

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions src/main/java/http/util/HttpRequestUtils.java
Original file line number Diff line number Diff line change
@@ -1,11 +1,52 @@
package http.util;

import responsefactory.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;

public class HttpRequestUtils {
/**
요청 메시지 해석에 관련된 도구들
**/
private static final Logger log = Logger.getLogger(HttpRequestUtils.class.getName());

/**
* 쿼리스트링 해석 및 분리해서 반환하는 함수
* @param queryString
* @return paramMap에 queryString을 key, value로 분리해서 map 형태로 반환
*/
public Map<String,String> parseQueryString(String queryString){
Map<String,String> paramMap = new HashMap<>();
if(!queryString.isEmpty()){
String[] parts=queryString.split("&");
for(String part:parts) {
String[] keyValue = part.split("=");
String key=keyValue[0]; //key는 아이디, 비번, 이름, 이메일 주소 "타입 정보!"
log.log(Level.INFO,key);
String value = keyValue.length > 1 ? keyValue[1] : ""; //value는 해당 타입에 대한 실제 데이터 정보!
//{key: value, key: value, key: value, key: value} 형식!
// try{
// value= URLDecoder.decode(value,"UTF-8");
// log.log(Level.INFO,value);
// }catch (UnsupportedEncodingException e){
// e.printStackTrace();
// }
paramMap.put(key,value);
}
}
return paramMap;
}

/**
* 강의로부터 받은 코드 -> 아직 이해가 잘 안됨
*/
public static Map<String, String> parseQueryParameter(String queryString) {
try {
String[] queryStrings = queryString.split("&");
Expand Down
46 changes: 45 additions & 1 deletion src/main/java/http/util/IOUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,64 @@

import java.io.BufferedReader;
import java.io.IOException;
import java.util.logging.Level;

public class IOUtils {
/**
* 요청 메세지의 body 부분을 읽는 함수
*
* @param br
* socket으로부터 가져온 InputStream
*
* @param contentLength
* 헤더의 Content-Length의 값이 들어와야한다.
*
*/
public static String readData(BufferedReader br, int contentLength) throws IOException {
char[] body = new char[contentLength];
br.read(body, 0, contentLength);
return String.copyValueOf(body);
}

/**
* 응답메세지에서 헤더 부분의 Content-Length 부분을 찾아서 반환하는 함수
*
* @param br
* @return
* @throws IOException
*
*/

public static Integer getContentLength(BufferedReader br) throws IOException {
Integer contentLength = 0;
while (true) {
//content-length 추출 반복문
final String line = br.readLine();
if (line.equals("")) {
break;
}
// header info
if (line.startsWith("Content-Length")) {
contentLength = Integer.parseInt(line.split(": ")[1]);
}
}
return contentLength;
}

public static Boolean checkCoockie(BufferedReader br) throws IOException {
Boolean CookieExists=false;
while (true) {
//content-length 추출 반복문
final String line = br.readLine();
if (line.equals("")) {
break;
}
// header info
if (line.startsWith("Cookie")) {
if(line.split(": ")[1].equals("logined=true")){
CookieExists=true;
}
}
}
return CookieExists;
}
}
21 changes: 21 additions & 0 deletions src/main/java/responsefactory/ResponseBody.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package responsefactory;

import java.io.DataOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ResponseBody {
/**
* 응답메세지의 바디 부분을 반화해주는 클래스
*/
private static final Logger log = Logger.getLogger(ResponseBody.class.getName());
public void responseBody(DataOutputStream dos, byte[] body) {
try {
dos.write(body, 0, body.length);
dos.flush();
} catch (IOException e) {
log.log(Level.SEVERE, e.getMessage());
}
}
}
70 changes: 70 additions & 0 deletions src/main/java/responsefactory/ResponseHeader.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package responsefactory;

import java.io.DataOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;


public class ResponseHeader {
/**
* 상태코드에 따라 응답메세지의 헤더를 반환해주는 함수를 분리
*/
private static final Logger log = Logger.getLogger(ResponseHeader.class.getName());
public void response200Header(DataOutputStream dos, int lengthOfBodyContent) {

/*** 단순 조회에 대한 성공 응답 코드 200 ***/

try {
dos.writeBytes("HTTP/1.1 200 OK \r\n");
dos.writeBytes("Content-Type: text/html;charset=utf-8\r\n");
dos.writeBytes("Content-Length: " + lengthOfBodyContent + "\r\n");
dos.writeBytes("\r\n");
} catch (IOException e) {
log.log(Level.SEVERE, e.getMessage());
}
}

public void responseCSS200Header(DataOutputStream dos, int lengthOfBodyContent) {

/*** 단순 조회에 대한 성공 응답 코드 200 ***/

try {
dos.writeBytes("HTTP/1.1 200 OK \r\n");
dos.writeBytes("Content-Type: text/css;charset=utf-8\r\n");
dos.writeBytes("Content-Length: " + lengthOfBodyContent + "\r\n");
dos.writeBytes("\r\n");
} catch (IOException e) {
log.log(Level.SEVERE, e.getMessage());
}
}

public void response302Header(DataOutputStream dos, String redirectURI) {

/*** 페이지 리다이렉팅에 대한 응답 코드 302 ***/

try{
dos.writeBytes("HTTP/1.1 302 FOUND\r\n");
dos.writeBytes("Location: "+redirectURI+"\r\n");
dos.writeBytes("Content-Length: 0\r\n");
dos.writeBytes("\r\n");
}catch (IOException e){
log.log(Level.SEVERE,e.getMessage());
}
}

public void response302LoginSuccessHeader(DataOutputStream dos, String cookieValue, String redirectURI){

/*** 로그인 성공 후 쿠키 추가 및 페이지 리다이렉팅에 대한 응답 코드 302 ***/

try{
dos.writeBytes("HTTP/1.1 302 FOUND\r\n");
dos.writeBytes("Location: "+redirectURI+"\r\n");
dos.writeBytes("Set-Cookie: "+cookieValue+"\r\n");
dos.writeBytes("Content-Length: 0\r\n");
dos.writeBytes("\r\n");
}catch (IOException e){
log.log(Level.SEVERE,e.getMessage());
}
}
}
Loading