본문 바로가기
블로그 이미지

방문해 주셔서 감사합니다! 항상 행복하세요!

  
   - 문의사항은 메일 또는 댓글로 언제든 연락주세요.
   - "해줘","답 내놔" 같은 질문은 답변드리지 않습니다.
   - 메일주소 : lts06069@naver.com


Spring framework

Spring프레임워크 415, 400 오류 (Requestbody, RequestParam)

야근없는 행복한 삶을 위해 ~
by 마샤와 곰 2019. 7. 9.

 

 

HttpClient를 활용해서 다른 서버에 요청을 걸어 데이터를 가져오는 기능을 구현중에 있었다.

해당 서버에서도 SpringFramework를 활용한 작업이라 금방 할 것 같았는데..

Request매핑에서 간혹 오류가 발생 하였다.

	@RequestMapping(value = "/good.do")  
	@ResponseBody
	public synchronized String good(@RequestParam HashMap<Object, Object> param){
		return "SUCC";
	}		

	@RequestMapping(value = "/error.do")  
	@ResponseBody
	public synchronized String error(@RequestBody HashMap<Object, Object> param){
		return "SUCC";
	}		

위 코드를 보면 Request를 매핑하는게 조금 다른데..RequestParam인 경우에는 별 문제없이 서로 데이터를 주고받는게 원활 했는데..RequestBody 에노테이션의 메소드에서는 415 또는 400오류가 자꾸 발생 하였다.

 

요청하는 데이터 형식이 올바르지 않다는 오류이므로 요청하는 데이터 형식을 보낼 때 제대로(?) 가공해서 보내면 문제없이 잘 보내어 진다.

* 여기서는 아피치 HttpClient를 사용하였다.

		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.4</version>
		</dependency>
		<dependency>
		    <groupId>org.codehaus.groovy</groupId>
		    <artifactId>groovy-json</artifactId>
		    <version>2.0.0-rc-4</version>
		</dependency>
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;

import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;

import org.apache.http.util.EntityUtils;

public class HTTPTest {

	private static final String USER_AGENT = "Mozila/5.0";
    private static final String GET_URL = "http://localhost:8080/error.do"; 



	
	public static void main(String[] args) {
		try {
			sendPost();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


    public static void sendPost() throws Exception{
    	CloseableHttpClient httpclient = HttpClients.createDefault();
    	HttpPost httpPost = new HttpPost(GET_URL);
    	
    	httpPost.addHeader("User-Agent", USER_AGENT);
    	
    	groovy.json.JsonBuilder builder = new groovy.json.JsonBuilder();

    	HashMap<Object, Object> param = new HashMap<Object, Object>();
    	param.put("_id", "asdfasdf");
    	param.put("status_a", "ggggbebe");
    	
    	builder.call(param);  //파라미터를 json형식으로 가공하는 구간.
    	StringEntity requestEntity = new StringEntity(builder.toString() , "utf-8");
    	requestEntity.setContentType(new BasicHeader("Content-Type", "application/json"));
    	httpPost.setEntity(requestEntity);
   	
    	CloseableHttpResponse response2 = httpclient.execute(httpPost);  //시작!
    	try {
    	    HttpEntity entity2 = response2.getEntity();
    		BufferedReader bf = null;
    		InputStreamReader in = null;
    		StringBuffer response = new StringBuffer();
    		try {
    			in = new InputStreamReader(entity2.getContent(), "UTF-8");
    			bf = new BufferedReader(in);
    			String inputLine;
    			while ((inputLine = bf.readLine()) != null) {
    				response.append(inputLine);
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally{
    			if(in != null){
    				in.close();	
    			}
    			if(bf != null){
    				bf.close();	
    			}
    		}    	    
    		System.out.println(response.toString());  //결과 내용
    	    EntityUtils.consume(entity2);
    	} finally {
    	    response2.close();
    	}
    }
}

저기서 핵심은 JsonBuilder를 통해서 전송하는 내용을 이쁘게(?) 만드는 부분이다.

Node.js였다면 편했을텐데...

반응형
* 위 에니메이션은 Html의 캔버스(canvas)기반으로 동작하는 기능 입니다. Html 캔버스 튜토리얼 도 한번 살펴보세요~ :)
* 직접 만든 Html 캔버스 애니메이션 도 한번 살펴보세요~ :)

댓글