반응형
Recent Posts
Recent Comments
관리 메뉴

개발잡부

[java] HttpUtils 본문

JAVA/java

[java] HttpUtils

닉의네임 2022. 1. 18. 10:51
반응형
package com.etoos.datalake.utils;

import com.google.gson.Gson;
import org.apache.tomcat.util.json.JSONParser;
import org.apache.tomcat.util.json.ParseException;
import org.json.simple.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;


public class HttpUtils {

    private static String  encoding ="UTF-8";

    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;
        }
    }


    public synchronized static String get(String url, Object parameters){

        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();


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

            if(encoding!=null){
                con.setRequestProperty("Accept-Charset", encoding);
            }

            if(parameters!=null){
                con.setDoOutput(true);
                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);
            }
        }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 > java' 카테고리의 다른 글

[java] picocli java sample  (0) 2022.03.22
[java] HTTP 통신하기  (0) 2022.01.18
Json 파일 읽기 - json.simple  (0) 2022.01.11
[selenium] 동적생성 웹페이지 크롤링  (0) 2022.01.07
[selenium] Selenium 설치  (0) 2022.01.07
Comments