Example usage for java.net HttpURLConnection setDoInput

List of usage examples for java.net HttpURLConnection setDoInput

Introduction

In this page you can find the example usage for java.net HttpURLConnection setDoInput.

Prototype

public void setDoInput(boolean doinput) 

Source Link

Document

Sets the value of the doInput field for this URLConnection to the specified value.

Usage

From source file:io.andyc.papercut.api.PrintApi.java

/**
 * Queries the remote Papercut server to get the status of the file
 *
 * e.g.//  ww  w .  jav  a 2  s.com
 *
 * {"status":{"code":"hold-release","complete":false,"text":"Held in a
 * queue","formatted":"Held in a queue"},"documentName":"test.rtf",
 * "printer":"Floor1 (Full Colour)","pages":1,"cost":"$0.10"}
 *
 * @param printJob {PrintJob} - the file to check the status on
 *
 * @return {String} - JSON String which includes file metadata
 *
 * @throws NoStatusURLSetException
 * @throws IOException
 */
public static PrintStatusData getFileStatus(PrintJob printJob) throws NoStatusURLSetException, IOException {
    if (Objects.equals(printJob.getStatusCheckURL(), "") || printJob.getStatusCheckURL() == null) {
        throw new NoStatusURLSetException();
    }

    // from: http://stackoverflow.com/a/29889139/2605221
    StringBuilder stringBuffer = new StringBuilder("");
    URL url = new URL(printJob.getStatusCheckURL());
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty("User-Agent", "");
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Accept", "application/json");
    connection.setDoInput(true);
    connection.connect();

    InputStream inputStream = connection.getInputStream();

    BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
    String line = "";
    while ((line = rd.readLine()) != null) {
        stringBuffer.append(line);
    }
    return new ObjectMapper().readValue(stringBuffer.toString(), PrintStatusData.class);
}

From source file:Main.java

public static String postMultiPart(String urlTo, String post, String filepath, String filefield)
        throws ParseException, IOException {
    HttpURLConnection connection = null;
    DataOutputStream outputStream = null;
    InputStream inputStream = null;

    String twoHyphens = "--";
    String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****";
    String lineEnd = "\r\n";

    String result = "";

    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;

    String[] q = filepath.split("/");
    int idx = q.length - 1;

    try {//ww w .  j a  v  a  2  s. c  om
        File file = new File(filepath);
        FileInputStream fileInputStream = new FileInputStream(file);

        URL url = new URL(urlTo);
        connection = (HttpURLConnection) url.openConnection();

        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);

        connection.setRequestMethod("POST");
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("User-Agent", "Android Multipart HTTP Client 1.0");
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

        outputStream = new DataOutputStream(connection.getOutputStream());
        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
        outputStream.writeBytes("Content-Disposition: form-data; name=\"" + filefield + "\"; filename=\""
                + q[idx] + "\"" + lineEnd);
        outputStream.writeBytes("Content-Type: image/jpeg" + lineEnd);
        outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
        outputStream.writeBytes(lineEnd);

        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];

        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        while (bytesRead > 0) {
            outputStream.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

        outputStream.writeBytes(lineEnd);

        // Upload POST Data
        String[] posts = post.split("&");
        int max = posts.length;
        for (int i = 0; i < max; i++) {
            outputStream.writeBytes(twoHyphens + boundary + lineEnd);
            String[] kv = posts[i].split("=");
            outputStream.writeBytes("Content-Disposition: form-data; name=\"" + kv[0] + "\"" + lineEnd);
            outputStream.writeBytes("Content-Type: text/plain" + lineEnd);
            outputStream.writeBytes(lineEnd);
            outputStream.writeBytes(kv[1]);
            outputStream.writeBytes(lineEnd);
        }

        outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

        inputStream = connection.getInputStream();
        result = convertStreamToString(inputStream);

        fileInputStream.close();
        inputStream.close();
        outputStream.flush();
        outputStream.close();

        return result;
    } catch (Exception e) {
        Log.e("MultipartRequest", "Multipart Form Upload Error");
        e.printStackTrace();
        return "error";
    }
}

From source file:eu.crowdrec.contest.sender.RequestSender.java

/**
 * Send a line from a logFile to an HTTP server (single-threaded).
 * /*www  .j a  v a2s  . co m*/
 * @param logline the line that should by sent
 * 
 * @param connection the connection to the http server, must not be null
 * 
 * @return the response or null (if an error has been detected)
 */
static private String excutePost(final String logline, final String serverURL) {

    // split the logLine into several token
    String[] token = logline.split("\t");

    String type = token[0];
    String property = token[3];
    String entity = token[4];

    // encode the content as URL parameters.
    String urlParameters = "";
    try {
        urlParameters = String.format("type=%s&properties=%s&entities=%s", URLEncoder.encode(type, "UTF-8"),
                URLEncoder.encode(property, "UTF-8"), URLEncoder.encode(entity, "UTF-8"));
    } catch (UnsupportedEncodingException e1) {
        logger.warn(e1.toString());
    }

    // initialize a HTTP connection to the server
    // reuse of connection objects is delegated to the JVM
    HttpURLConnection connection = null;

    try {
        final URL url = new URL(serverURL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Content-Language", "en-US");
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));

        // Send request
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        // Get Response
        BufferedReader rd = null;
        InputStream is = null;
        try {
            is = connection.getInputStream();
            rd = new BufferedReader(new InputStreamReader(is));

            StringBuffer response = new StringBuffer();
            for (String line = rd.readLine(); line != null; line = rd.readLine()) {
                response.append(line);
                response.append(" ");
            }
            return response.toString();
        } catch (IOException e) {
            logger.warn("receivind response failed, ignored.");
        } finally {
            if (is != null) {
                is.close();
            }
            if (rd != null) {
                rd.close();
            }
        }
    } catch (MalformedURLException e) {
        System.err.println("invalid server URL, program stopped.");
        System.exit(-1);
    } catch (IOException e) {
        System.err.println("i/o error connecting the http server, program stopped. e=" + e);
        System.exit(-1);
    } catch (Exception e) {
        System.err.println("general error connecting the http server, program stopped. e:" + e);
        e.printStackTrace();
        System.exit(-1);
    } finally {
        // close the connection
        if (connection != null) {
            connection.disconnect();
        }
    }
    return null;
}

From source file:xqpark.ParkApi.java

/**
 * API?/*from  w  w w.  j a v a2s . com*/
 * @param ?url
 * @return APIJSON?
 * @throws JSONException
 * @throws IOException 
 * @throws ParseException 
 */
public static JSONObject loadJSON(String url) throws JSONException {
    StringBuilder json = new StringBuilder();
    try {
        URLEncoder.encode(url, "UTF-8");
        URL urlObject = new URL(url);
        HttpURLConnection uc = (HttpURLConnection) urlObject.openConnection();

        uc.setDoOutput(true);//  URL 
        uc.setDoInput(true);//  URL 
        uc.setUseCaches(false);
        uc.setRequestMethod("POST");

        BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream(), "utf-8"));
        String inputLine = null;
        while ((inputLine = in.readLine()) != null) {
            json.append(inputLine);
        }
        in.close();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    JSONObject responseJson = new JSONObject(json.toString());
    return responseJson;
}

From source file:ict.servlet.UploadToServer.java

public static int upLoad2Server(String sourceFileUri) {
    String upLoadServerUri = "http://vbacdu.ddns.net:8080/WBS/newjsp.jsp";
    // String [] string = sourceFileUri;
    String fileName = sourceFileUri;
    int serverResponseCode = 0;

    HttpURLConnection conn = null;
    DataOutputStream dos = null;//from   w  w  w  . j  av  a 2s .com
    DataInputStream inStream = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    String responseFromServer = "";

    File sourceFile = new File(sourceFileUri);
    if (!sourceFile.isFile()) {

        return 0;
    }
    try { // open a URL connection to the Servlet
        FileInputStream fileInputStream = new FileInputStream(sourceFile);
        URL url = new URL(upLoadServerUri);
        conn = (HttpURLConnection) url.openConnection(); // Open a HTTP  connection to  the URL
        conn.setDoInput(true); // Allow Inputs
        conn.setDoOutput(true); // Allow Outputs
        conn.setUseCaches(false); // Don't use a Cached Copy
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("ENCTYPE", "multipart/form-data");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        conn.setRequestProperty("uploaded_file", fileName);
        dos = new DataOutputStream(conn.getOutputStream());

        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + fileName + "\""
                + lineEnd);
        dos.writeBytes(lineEnd);

        bytesAvailable = fileInputStream.available(); // create a buffer of  maximum size

        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];

        // read file and write it into form...
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);

        while (bytesRead > 0) {
            dos.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

        // send multipart form data necesssary after file data...
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

        // Responses from the server (code and message)
        serverResponseCode = conn.getResponseCode();
        String serverResponseMessage = conn.getResponseMessage();

        m_log.info("Upload file to server" + "HTTP Response is : " + serverResponseMessage + ": "
                + serverResponseCode);
        // close streams
        m_log.info("Upload file to server" + fileName + " File is written");
        fileInputStream.close();
        dos.flush();
        dos.close();
    } catch (MalformedURLException ex) {
        //         ex.printStackTrace();
        m_log.error("Upload file to server" + "error: " + ex.getMessage(), ex);
    } catch (Exception e) {
        //      e.printStackTrace();
    }
    //this block will give the response of upload link
    /* try {
      BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      String line;
      while ((line = rd.readLine()) != null) {
      m_log.info("Huzza" + "RES Message: " + line);
      }
      rd.close();
      } catch (IOException ioex) {
      m_log.error("Huzza" + "error: " + ioex.getMessage(), ioex);
      }*/
    return serverResponseCode; // like 200 (Ok)

}

From source file:com.mhs.hboxmaintenanceserver.utils.Utils.java

/**
 * Send form post//  www .j  av  a2s.c o  m
 *
 * @param form
 * @param forms
 * @return
 * @throws MalformedURLException
 * @throws IOException
 */
public static Form sendPostForm(Form form, Form[] forms) throws MalformedURLException, IOException {
    URL obj = new URL(form.getUrl().trim());
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    con.setDoInput(true);

    if (forms != null) {
        con.setDoOutput(true);

        // optional default is GET
        con.setRequestMethod("POST");
    }

    //add request header
    con.setRequestProperty("User-Agent", DefaultConfig.USER_AGENT);
    con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
    con.setRequestProperty("Referer", form.getReferer());
    con.setRequestProperty("Origin", form.getOrigin());
    con.setRequestProperty("Host", form.getHost());

    if (COOKIE != null) {
        try {
            con.setRequestProperty("Cookie", COOKIE);
        } catch (Exception ex) {
            DCXLogger.error(Utils.class, Level.SEVERE, ex);
        }
    }

    String urlParameters = "";

    if (forms != null) {
        for (Form fb : forms) {
            urlParameters += "&" + fb.getKey() + "=" + fb.getValue();
        }

        urlParameters = urlParameters.substring(1);

        try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
            wr.writeBytes(urlParameters);
            wr.close();
        }
    }
    if (con.getHeaderField("Set-Cookie") != null) {
        COOKIE = con.getHeaderField("Set-Cookie");
    }

    Form form1 = new Form();
    form1.setResponseCode(con.getResponseCode());
    StringBuilder response = new StringBuilder();

    if (form1.getResponseCode() == 200) {
        try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
            String inputLine;

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

        form1.setResult(response.toString());
    }
    return form1;
}

From source file:com.zzl.zl_app.cache.Utility.java

public static String uploadFile(File file, String RequestURL, String fileName) {
    Tools.log("IO", "RequestURL:" + RequestURL);
    String result = null;/*from   ww  w . j  a  v a  2s  .co  m*/
    String BOUNDARY = UUID.randomUUID().toString(); //  ??
    String PREFIX = "--", LINE_END = "\r\n";
    String CONTENT_TYPE = "multipart/form-data"; // 

    try {
        URL url = new URL(RequestURL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(Utility.SET_SOCKET_TIMEOUT);
        conn.setConnectTimeout(Utility.SET_CONNECTION_TIMEOUT);
        conn.setDoInput(true); // ??
        conn.setDoOutput(true); // ??
        conn.setUseCaches(false); // ??
        conn.setRequestMethod("POST"); // ?
        conn.setRequestProperty("Charset", CHARSET); // ?
        conn.setRequestProperty("connection", "keep-alive");
        conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);

        if (file != null) {
            /**
             * ?
             */
            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
            StringBuffer sb = new StringBuffer();
            sb.append(PREFIX);
            sb.append(BOUNDARY);
            sb.append(LINE_END);
            /**
             * ?? name???key ?key ??
             * filename?????? :abc.png
             */
            sb.append("Content-Disposition: form-data; name=\"voice\"; filename=\"" + file.getName() + "\""
                    + LINE_END);
            sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END);
            sb.append(LINE_END);
            dos.write(sb.toString().getBytes());
            Tools.log("FileSize", "file:" + file.length());
            InputStream is = new FileInputStream(file);
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = is.read(bytes)) != -1) {
                dos.write(bytes, 0, len);
                Tools.log("FileSize", "size:" + len);
            }

            dos.write(LINE_END.getBytes());
            byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
            dos.write(end_data);
            dos.flush();
            dos.close();
            is.close();
            /**
             * ??? 200=? ?????
             */
            int res = conn.getResponseCode();
            Tools.log("IO", "ResponseCode:" + res);
            if (res == 200) {
                InputStream input = conn.getInputStream();
                StringBuffer sb1 = new StringBuffer();
                int ss;
                while ((ss = input.read()) != -1) {
                    sb1.append((char) ss);
                }
                result = sb1.toString();
            }

        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}

From source file:com.fota.Link.sdpApi.java

public static String getNcnInfo(String CTN) throws JDOMException {
    String resultStr = "";
    String logData = "";
    try {/*from  w w w. ja v a2  s  .c  o m*/
        String endPointUrl = PropUtil.getPropValue("sdp.oif516.url");

        String strRequest = "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' "
                + "xmlns:oas='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd'"
                + " xmlns:sdp='http://kt.com/sdp'>" + "     <soapenv:Header>" + "         <oas:Security>"
                + "             <oas:UsernameToken>" + "                 <oas:Username>"
                + PropUtil.getPropValue("sdp.id") + "</oas:Username>" + "                 <oas:Password>"
                + PropUtil.getPropValue("sdp.pw") + "</oas:Password>" + "             </oas:UsernameToken>"
                + "         </oas:Security>" + "     </soapenv:Header>"

                + "     <soapenv:Body>" + "         <sdp:getBasicUserInfoAndMarketInfoRequest>"
                + "         <!--You may enterthe following 6 items in any order-->"
                + "             <sdp:CALL_CTN>" + CTN + "</sdp:CALL_CTN>"
                + "         </sdp:getBasicUserInfoAndMarketInfoRequest>\n" + "     </soapenv:Body>\n"
                + "</soapenv:Envelope>";

        logData = "\r\n---------- Get Ncn Req Info start ----------\r\n";
        logData += " get Ncn Req Info - endPointUrl : " + endPointUrl;
        logData += "\r\n get Ncn Req Info - Content-type : text/xml;charset=utf-8";
        logData += "\r\n get Ncn Req Info - RequestMethod : POST";
        logData += "\r\n get Ncn Req Info - xml : " + strRequest;
        logData += "\r\n---------- Get Ncn Req Info end ----------";

        logger.info(logData);

        // connection
        URL url = new URL(endPointUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("Content-type", "text/xml;charset=utf-8");
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.connect();

        // output
        OutputStream os = connection.getOutputStream();
        // os.write(strRequest.getBytes(), 0, strRequest.length());
        os.write(strRequest.getBytes("utf-8"));
        os.flush();
        os.close();

        // input
        InputStream is = connection.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
        String line = "";
        String resValue = "";
        String parseStr = "";
        while ((line = br.readLine()) != null) {
            System.out.println(line);
            parseStr = line;

        }

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        InputSource temp = new InputSource();
        temp.setCharacterStream(new StringReader(parseStr));
        Document doc = builder.parse(temp); //xml?

        NodeList list = doc.getElementsByTagName("*");

        int i = 0;
        Element element;
        String contents;

        String contractNum = "";
        String customerId = "";
        while (list.item(i) != null) {
            element = (Element) list.item(i);
            if (element.hasChildNodes()) {
                contents = element.getFirstChild().getNodeValue();
                System.out.println(element.getNodeName() + " / " + element.getFirstChild().getNodeName());

                if (element.getNodeName().equals("sdp:NS_CONTRACT_NUM")) {
                    //                  resultStr = element.getFirstChild().getNodeValue();
                    contractNum = element.getFirstChild().getNodeValue();
                }
                if (element.getNodeName().equals("sdp:NS_CUSTOMER_ID")) {
                    customerId = element.getFirstChild().getNodeValue();
                }

                //               System.out.println(" >>>>> " + contents);
            }
            i++;
        }

        //         System.out.println("contractNum : " + contractNum + " / cusomerId : " + customerId);

        resultStr = getNcnFromContractnumAndCustomerId(contractNum, customerId);
        //         System.out.println("ncn : " + resultStr);

        //resultStr = resValue;         
        //         resultStr = java.net.URLDecoder.decode(resultStr, "euc-kr");
        connection.disconnect();

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

    return resultStr;
}

From source file:eu.geopaparazzi.library.network.NetworkUtilities.java

/**
 * Send a file via HTTP POST with basic authentication.
 * //from  w ww. j  a va  2  s.  c  o m
 * @param urlStr the server url to POST to.
 * @param file the file to send.
 * @param user the user or <code>null</code>.
 * @param password the password or <code>null</code>.
 * @return the return string from the POST.
 * @throws Exception
 */
public static String sendFilePost(String urlStr, File file, String user, String password) throws Exception {
    BufferedOutputStream wr = null;
    FileInputStream fis = null;
    HttpURLConnection conn = null;
    try {
        fis = new FileInputStream(file);
        long fileSize = file.length();
        // Authenticator.setDefault(new Authenticator(){
        // protected PasswordAuthentication getPasswordAuthentication() {
        // return new PasswordAuthentication("test", "test".toCharArray());
        // }
        // });
        conn = makeNewConnection(urlStr);
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        // conn.setChunkedStreamingMode(0);
        conn.setUseCaches(true);

        // conn.setRequestProperty("Accept-Encoding", "gzip ");
        // conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Type", "application/x-zip-compressed");
        // conn.setRequestProperty("Content-Length", "" + fileSize);
        // conn.setRequestProperty("Connection", "Keep-Alive");

        if (user != null && password != null) {
            conn.setRequestProperty("Authorization", getB64Auth(user, password));
        }
        conn.connect();

        wr = new BufferedOutputStream(conn.getOutputStream());
        long bufferSize = Math.min(fileSize, maxBufferSize);

        if (GPLog.LOG)
            GPLog.addLogEntry(TAG, "BUFFER USED: " + bufferSize);
        byte[] buffer = new byte[(int) bufferSize];
        int bytesRead = fis.read(buffer, 0, (int) bufferSize);
        long totalBytesWritten = 0;
        while (bytesRead > 0) {
            wr.write(buffer, 0, (int) bufferSize);
            totalBytesWritten = totalBytesWritten + bufferSize;
            if (totalBytesWritten >= fileSize)
                break;

            bufferSize = Math.min(fileSize - totalBytesWritten, maxBufferSize);
            bytesRead = fis.read(buffer, 0, (int) bufferSize);
        }
        wr.flush();

        String responseMessage = conn.getResponseMessage();

        if (GPLog.LOG)
            GPLog.addLogEntry(TAG, "POST RESPONSE: " + responseMessage);
        return responseMessage;
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    } finally {
        if (wr != null)
            wr.close();
        if (fis != null)
            fis.close();
        if (conn != null)
            conn.disconnect();
    }
}

From source file:com.fota.Link.sdpApi.java

public static String getCtnInfo(String ncn) throws JDOMException {
    String resultStr = "";
    String logData = "";
    try {/*ww w  .  java2s.  c o m*/
        String cpId = PropUtil.getPropValue("sdp3g.id");
        String cpPw = PropUtil.getPropValue("sdp3g.pw");
        String authorization = cpId + ":" + cpPw;
        logData = "\r\n---------- Get Ctn Req Info start ----------\r\n";
        logData += " getCtnRequestInfo - authorization : " + authorization;
        byte[] encoded = Base64.encodeBase64(authorization.getBytes());
        authorization = new String(encoded);

        String contractType = "0";
        String contractNum = ncn.substring(0, 9);
        String customerId = ncn.substring(10, ncn.length() - 1);

        JSONObject reqJObj = new JSONObject();
        reqJObj.put("transactionid", "");
        reqJObj.put("sequenceno", "");
        reqJObj.put("userid", "");
        reqJObj.put("screenid", "");
        reqJObj.put("CONTRACT_NUM", contractNum);
        reqJObj.put("CUSTOMER_ID", customerId);
        reqJObj.put("CONTRACT_TYPE", contractType);

        authorization = "Basic " + authorization;

        String endPointUrl = PropUtil.getPropValue("sdp.oif555.url");

        logData += "\r\n getCtnRequestInfo - endPointUrl : " + endPointUrl;
        logData += "\r\n getCtnRequestInfo - authorization(encode) : " + authorization;
        logData += "\r\n getCtnRequestInfo - Content-type : application/json";
        logData += "\r\n getCtnRequestInfo - RequestMethod : POST";
        logData += "\r\n getCtnRequestInfo - json : " + reqJObj.toString();
        logData += "\r\n---------- Get Ctn Req Info end ----------";

        logger.info(logData);

        // connection
        URL url = new URL(endPointUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setRequestProperty("Authorization", authorization);
        connection.setRequestProperty("Content-type", "application/json");

        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.connect();

        // output
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(reqJObj.toJSONString());
        wr.flush();
        wr.close();

        // input
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine = "";
        StringBuffer response = new StringBuffer();

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

        in.close();

        JSONParser jsonParser = new JSONParser();
        JSONObject respJsonObject = (JSONObject) jsonParser.parse(response.toString());

        //         String respTransactionId = (String) respJsonObject.get("transactionid");
        //         String respSequenceNo = (String) respJsonObject.get("sequenceno");
        //         String respReturnCode = (String) respJsonObject.get("returncode");
        //         String respReturnDescription = (String) respJsonObject.get("returndescription");
        //         String respErrorCode = (String) respJsonObject.get("errorcode");
        //         String respErrorDescription = (String) respJsonObject.get("errordescription");
        String respCtn = (String) respJsonObject.get("ctn");
        //         String respSubStatus = (String) respJsonObject.get("sub_status");
        //         String respSubStatusDate = (String) respJsonObject.get("sub_status_date");

        resultStr = respCtn;

        //resultStr = resValue;         
        //         resultStr = java.net.URLDecoder.decode(resultStr, "euc-kr");
        connection.disconnect();

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

    return resultStr;
}