본문 바로가기

Dev/Orvercome 3sec memory

Server to Server Http POST 요청 시 파라미터 처리방법 2가지와 Entity 클래스

728x90

#. 테스트 했을 때 성공한 방법


1. 일반적인 Form 파라미터 형식(?로 시작하고 &표시로 연결되는 일련의 스트링값) 전송

   - 반환 형식 json


import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; public class SimpleHttpPut { public static void main(String[] args) { HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost("http://vogellac2dm.appspot.com/register"); try {  

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);

nameValuePairs.add(new BasicNameValuePair("Email", "youremail"));  nameValuePairs .add(new BasicNameValuePair("Passwd", "yourpassword")); nameValuePairs.add(new BasicNameValuePair("accountType", "GOOGLE")); nameValuePairs.add(new BasicNameValuePair("source", "Google-cURL-Example")); nameValuePairs.add(new BasicNameValuePair("service", "ac2dm")); post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

/* 반환 값 스트링 처리  

BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line = ""; while ((line = rd.readLine()) != null) { System.out.println(line); }  */

/** json 형태 반환값 처리 **/

 ObjectMapper mapper = new ObjectMapper();

 JsonNode node = mapper.readTree(response.getEntity().getContent());

 int resultCode = mapper.readValue(node.get("resultCode"), Integer.class); 

} catch (IOException e) { e.printStackTrace(); } } }

※ 참조

http://www.vogella.com/articles/ApacheHttpClient/article.html



2. Json 형식({"Key":"value"}) 파라미터 전송

- 반환 형식 json

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.util.HashMap; import java.util.Iterator; import java.util.Set; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.log4j.Logger; public class ApacheHttpClient {

private Logger logger = Logger.getLogger(this.getClass());

  public String restPOST(String reqUrl, String reqParam, HashMap<String, Object> extendedHeader, String contentType) {

String serverResponse = new String();

try {

 

DefaultHttpClient httpClient = new DefaultHttpClient();

HttpPost postRequest = new HttpPost(reqUrl);

/** 추가 Header 필요한 경우 설정 **/ 

if(extendedHeader != null){

Set<String> keySet = (Set<String>)extendedHeader.keySet();

Iterator<String> headerKeys = keySet.iterator();

while(headerKeys.hasNext()){

String headerKey = headerKeys.next();

postRequest.addHeader(headerKey, (String)extendedHeader.get(headerKey));

}

}

/** requParam은 json 형태의 String value **/

StringEntity input = new StringEntity(reqParam, "UTF-8");

input.setContentType(contentType);

postRequest.setEntity(input);


/** 또는

StringEntity entity = new StringEntity(reqParam); entity.setContentEncoding(HTTP.UTF_8); entity.setContentType("application/json"); httpPost.setEntity(entity);

**/

HttpResponse response = httpClient.execute(postRequest);

serverResponse = catchResponse(response);

httpClient.getConnectionManager().shutdown();

} catch (MalformedURLException e) {

logger.error("########## ERROR IN REST POST - MalformedURLException : "+ this.getClass());

logger.error(e);

e.printStackTrace();

serverResponse = null;

}catch(IOException e) {;

logger.error("########## ERROR IN REST POST - IOException: "+ this.getClass());

logger.error(e);

e.printStackTrace();

serverResponse = null;

}catch(Exception e) {;

logger.error("########## ERROR IN REST POST - Exception : "+ this.getClass());

logger.error(e);

e.printStackTrace();

serverResponse = null;

}


return serverResponse;

}

private String catchResponse(HttpResponse response ) throws IOException{ String serverResponse = ""; if (response.getStatusLine().getStatusCode() != 200) { logger.error("\n########## Failed ##########\n HTTP error code : " + response.getStatusLine().getStatusCode() + "\n HTTP error reason :" + response.getStatusLine().getReasonPhrase()); if(response.getStatusLine().getStatusCode() != 400) return new String( ("{\"error\":\""+response.getStatusLine().getStatusCode() + response.getStatusLine().getReasonPhrase() +"\"}").getBytes(), "UTF-8"); } BufferedReader br = new BufferedReader( new InputStreamReader((response.getEntity().getContent()), "UTF-8")); String output; logger.debug("Output from Server .... \n"); while ((output = br.readLine()) != null) { serverResponse += output; logger.debug(output); } return serverResponse; }

}


1번과 2번에서 Header값이나 파라미터 값을 담는 Entity 종류가 다르다.

1번에서 나오는 org.apache.http.client.entity.UrlEncodedFormEntity

 Package org.apache.http.client.entity

Additional HTTP entity implementations that depend on HttpClient specific features.


▒ 참조

http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/entity/package-summary.html




 2번에서 나오는 org.apache.http.entity.StringEntity

 Package org.apache.http.entity

Common HTTP entity implementations.


 ▒ 참조 

http://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/entity/package-summary.html



글쓰기전까지 같은 패키지에 속하는 클래스일거라고 생각했는데 살짝 당황스럽다.


각 Entity 사용법에 따라 위의 두 가지 방법 말고, 다른 방법으로 POST 요청 시 파라미터를 보낼 수 있지 않을까.


보통 검색 시 나오는 Common Entity는 ByteArrayEntity, StringEntity (A self contained, repeatable entity that obtains its content from  a byte Array / a String. )는 비슷한 특성을 갖는다.

또 다른 종류의 클래스 중 FileEntity가 눈에 띈다. 파일을 어떻게 처리하는 거지?