ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [java] Http get,post 통신
    Java/Basic 2019. 1. 28. 18:28
    반응형

    너무 만들기 쉽기에 맨날 안만들어놔서 허구언날 프로젝트할때마다 만드던게 get/post 통신 같다. 


    하지만 만들때 마다 생각이 든것이 Apache 에서 제공하는 라이브러리를  쓰는게 아니라 순수 jdk 에서 지원되느걸 쓸수 없을까였다. 


    java 라면 왠지 있을거 같은데 하고 찾아보니... httpclient 라는 익숙한녀석이 있었다. 순간 Apache 꺼 아닌가.. 라는 생각을 했는데 ... 충격적인건 


    jdk 1.1 부터 이기능이 제공 됬다고 한다. 무진장 오래됬다..... 


    jdk 1.8 이 나오면서 HttpClient 가 비동기 통신을 지원하게 되었고 굉장히 매력적인 녀식이 된거 같다. 

    ( 음...  Netty 같은걸로 비동기통신을 구현하는게 나을 거 같기도하다. ) 



    기본적으로 동기화/비동기화가 사용 가능하고 간단한통신등은 쉽게 구현이 가능하다. 



    import com.fasterxml.jackson.core.JsonProcessingException;
    import com.fasterxml.jackson.core.type.TypeReference;
    import com.fasterxml.jackson.databind.ObjectMapper;

    import java.io.IOException;
    import java.net.URI;
    import java.net.http.HttpClient;
    import java.net.http.HttpRequest;
    import java.net.http.HttpResponse;
    import java.nio.file.Paths;
    import java.util.List;
    import java.util.Map;
    import java.util.concurrent.CompletableFuture;
    import java.util.concurrent.CompletionException;

    import static java.net.http.HttpResponse.BodyHandlers.ofString;
    import static java.util.stream.Collectors.toList;

    public class HttpUtils {


    public Object get(String url) throws IOException, InterruptedException {
    HttpClient client = HttpClient.newHttpClient();
    HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create(url))
    .build();
    HttpResponse response =
    client.send( request , ofString() );
    return response.body();
    }


    public void getFile(String url, String file) throws IOException, InterruptedException {
    HttpClient client = HttpClient.newHttpClient();
    HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create(url))
    .build();
    HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofFile(Paths.get(file)));
    System.out.println();
    }

    public Object getAsync(String url ) {
    HttpClient client = HttpClient.newHttpClient();
    HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create(url))
    .build();

    return client.sendAsync(request, ofString()).thenApply(HttpResponse::body);
    }

    public Object getAsyncFile(String url , String file ) {
    HttpClient client = HttpClient.newHttpClient();
    HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create(url))
    .build();

    return client.sendAsync(request, HttpResponse.BodyHandlers.ofFile(Paths.get(file))).thenApply(HttpResponse::body);
    }

    public Object post(String url , String data) throws IOException, InterruptedException {
    HttpClient client = HttpClient.newBuilder().build();
    HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create(url))
    .POST(HttpRequest.BodyPublishers.ofString(data))
    .build();

    HttpResponse<?> response = client.send(request, HttpResponse.BodyHandlers.discarding());
    return response.body();

    }

    public void mutilRequest(List<URI> uris) {
    HttpClient client = HttpClient.newHttpClient();
    List<HttpRequest> requests = uris.stream()
    .map(HttpRequest::newBuilder)
    .map(reqBuilder -> reqBuilder.build())
    .collect(toList());

    CompletableFuture.allOf(requests.stream()
    .map(request -> client.sendAsync(request, ofString()) )
    .toArray(CompletableFuture<?>[]::new))
    .join();

    }


    }

    샘플 예제를 보고 그대로 만들었다 ( 테스트는 아직안함.... 귀차니즘... 나중에 사용해보고 수정해될거 같다. )  openjdk 사이트에서 확인 했는데 생각보다 예졔가 잘나와있다. 단순해서 그런걸수도 모르겠다. 

    (https://openjdk.java.net/groups/net/httpclient/recipes.html) 


    예제 복붙하는 수준으로 만들었기 때문에 10분도 안걸렸던거 같다. 이것도 유틸리티 화해서 좀 다듬어서 사용해 봐야겠다. 잘안되면 Apache 라이브러리 다시 쓰는걸로 ... ^^



    ※ 기타 ※


    이전 사용하던 방식도 추가 ( 저장개념 ) 


    -post

    /**
    * Post 방식
    * 요청 방식 : Key-set , json 선택
    * 응답방식 : JSON
    * @param sendUrl
    * @param data
    * @param sendType ( "json" or "key" )
    * @return HashMap resData
    * @throws Exception
    */
    public HashMap post( String sendUrl , HashMap<String,Object> data , String sendType ) throws Exception {
    JSONObject jobj = null;
    URL url = new URL(sendUrl);
    Gson gson = new Gson();
    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
    conn.setRequestMethod("POST");
    byte[] postDataBytes = null ;

    if(sendType.equals("json")) {
    conn.setRequestProperty("Content-Type", "application/json");

    String strJson = gson.toJson(data);
    postDataBytes = strJson.getBytes("UTF-8");
    }else {
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    StringBuilder postData = new StringBuilder();
    for (HashMap.Entry<String, Object> param : data.entrySet()) {
    if (postData.length() != 0) postData.append('&');
    postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
    postData.append('=');
    postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
    }
    postDataBytes = postData.toString().getBytes("UTF-8");
    }

    if(postDataBytes !=null && postDataBytes.length != 0){
    conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
    conn.setDoOutput(true);
    conn.getOutputStream().write(postDataBytes);

    Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
    StringBuffer sf = new StringBuffer();

    for (int c; (c = in.read()) >= 0;) sf.append((char)c);
    conn.disconnect();

    String resStr = sf.toString();
    HashMap resMap = new HashMap();

    return gson.fromJson(resStr, resMap.getClass() ) ;
    }else {
    conn.disconnect();
    return null;
    }
    }

    - get

    /**
    * HTTP호출
    * @param url
    * @param parameters
    * @return String
    */
    public synchronized static String get(String url, Object parameters, String encoding){
    StringBuffer sb =
    new StringBuffer();

    URLConnection con = null;
    OutputStreamWriter osw = null;
    InputStreamReader isr = null;
    System.out.println("API 호출 : "+url);

    int readTimeout = 60000;
    int connectionTimeout = 60000;

    try{

    con =
    new URL(url).openConnection();
    /**
    * 소켓자원이 회수가 안되고 계속 생성되어서
    * Hang 상태에 빠지는 증세가 발생하여 아래 timeout 설정들을 추가
    */

    con.setConnectTimeout(readTimeout);
    con.setReadTimeout(connectionTimeout);

    if(encoding!=null){
    System.
    out.println("인코딩 설정 : "+encoding);
    con.setRequestProperty("Accept-Charset", encoding);
    }

    if(parameters!=null){
    con.setDoOutput(
    true);
    System.out.println("파라메터 : "+parameters.toString());
    osw = new OutputStreamWriter(con.getOutputStream());
    osw.write(parameters.toString());
    osw.flush();
    }
    isr =
    new InputStreamReader(con.getInputStream());
    BufferedReader br = new BufferedReader(isr);

    String tmp = "";
    while((tmp=br.readLine())!=null){
    sb.append(tmp)
    ;
    }
    System.
    out.println("결과값 : "+sb.toString());
    }catch(Exception e){
    e.printStackTrace()
    ;
    }finally{

    if(osw != null){
    try{
    osw.close()
    ;
    }catch(Exception e){
    e.printStackTrace()
    ;
    }
    }
    if(isr != null){
    try{
    isr.close()
    ;
    }catch(Exception e){
    e.printStackTrace()
    ;
    }
    }
    }
    return sb.toString();
    }


    반응형

    'Java > Basic' 카테고리의 다른 글

    Logback 시간과 system 시간이 다를때...  (0) 2019.06.25
    JVM( GC) 이해하기  (0) 2019.04.26
    BigDecimal (feat. 소수점 계산)  (1) 2019.03.26
    [java]날짜 더하기, 빼기 , 구하기  (0) 2019.01.28
Designed by Tistory.