본문 바로가기
FullStack/21. Java

[JAVA] HttpClient를 통한 JOSN 전송 및 JSP로 데이터 수신

by nakanara 2020. 12. 17.
반응형

Java

HttpClinet를 이용한 JSON 데이터 송신

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpcore</artifactId>
</dependency>

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>\
</dependency>
<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
</dependency>
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
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.BasicNameValuePair;
import org.json.simple.JSONValue;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public void sendData(String url, String jsonData) throws IOException {

  CloseableHttpClient client = null;
  BufferedReader in = null;
  StringBuffer result = new StringBuffer();

  try {
      client = HttpClients.createDefault();
      HttpPost httpPost = new HttpPost(url);

      // 헤더 설정이 필요한 경우
      //httpPost.setHeader("header_key", "header_value");

      // JSON 데이터를 추가.
      httpPost.setEntity(new StringEntity(jsonData, ContentType.APPLICATION_JSON));

      // Key / Value 속성으로 할 경우
      // List<NameValuePair> params = new ArrayList<NameValuePair>();
      // params.add(new BasicNameValuePair("key", "value"));
      // httpPost.setEntity(new UrlEncodedFormEntity(params));    

      // 실행
      CloseableHttpResponse httpresponse = client.execute(httpPost);

      // 결과 수신
      InputStream inputStream = (InputStream)httpresponse.getEntity().getContent();

      String inputLine = null;
      in = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));

      while((inputLine = in.readLine()) != null) {
          result.append(inputLine);
      }
  }catch(IOException ioe) {
      throw ioe;
  }finally {
      if(in != null) {
          try {
              in.close();
          } catch(IOException ioe) { throw ioe; }
      }
  }
}

JSP 페이지에서 Body 데이터 수신


StringBuffer data = new StringBuffer();
BufferedReader in = null;
String inputLine;

// body 에서 데이터 수신 후 
try {
  in = request.getReader();

  while((inputLine = in.readLine()) != null) {
    data.append(inputLine);
  }

} catch(IOException ex){
  throw ex;
} finally {
  if(in != null) {
    try {
      in.close();
    } catch(IOException e) {
      throw ex;
    }
  }
}

JSONObject json = null;
json = (JSONObject) JSONValue.parse(data.toString());

System.out.println(json.toString());
반응형