java 백엔드 제3자 서버 액세스

2146 단어 JavaWeb
public static String sendRequestManager(String url, String body) throws IOException {
  
    StringBuilder sb = new StringBuilder();
    String result = "";
    BufferedWriter writer = null;
    BufferedReader bd = null;

    URL u = new URL(url);
    HttpURLConnection hc = (HttpURLConnection) u.openConnection();
    // uc.setRequestMethod("GET");
    hc.setRequestMethod("POST");
    hc.setConnectTimeout(5000);
    hc.setReadTimeout(5000);

    hc.setRequestProperty("Content-Type", "application/Json; charset=UTF-8");

    hc.setDoInput(true);
    hc.setDoOutput(true);

    try {

        writer = new BufferedWriter(new OutputStreamWriter(hc.getOutputStream(), "UTF-8"));
        writer.write(body);
        writer.close();

        if (hc.getResponseCode() == 200){
            bd = new BufferedReader(new InputStreamReader(hc.getInputStream(), "utf-8"));
            String s = null;
            while ((s = bd.readLine()) != null) {
                sb.append(s);
            }
            bd.close();
        }else if (hc.getResponseCode() == 301 || hc.getResponseCode() == 302) {
            //  
            String location = hc.getHeaderField("Location");
            URL u1 = new URL(location);
            HttpURLConnection hc1 = (HttpURLConnection) u1.openConnection();
            hc1.setRequestMethod("POST");
            hc1.setConnectTimeout(5000);
            hc1.setReadTimeout(5000);
            if (hc1.getResponseCode() == 200) {
                bd = new BufferedReader(new InputStreamReader(hc1.getInputStream(), "utf-8"));
                String s = null;
                while ((s = bd.readLine()) != null) {
                    sb.append(s);
                }
                bd.close();
            }
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (bd != null) {
            bd.close();
        }
        if (writer != null) {

            writer.close();
        }
    }

    result = sb.toString();

    return result;
}

좋은 웹페이지 즐겨찾기