Example usage for java.net HttpURLConnection setRequestMethod

List of usage examples for java.net HttpURLConnection setRequestMethod

Introduction

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

Prototype

public void setRequestMethod(String method) throws ProtocolException 

Source Link

Document

Set the method for the URL request, one of:
  • GET
  • POST
  • HEAD
  • OPTIONS
  • PUT
  • DELETE
  • TRACE
are legal, subject to protocol restrictions.

Usage

From source file:com.kiwiteam.nomiddleman.TourPageActivity.java

/**
 * Checks if link is active/*from  w  ww .  j av  a  2  s .co m*/
 * @param urlString
 * @return
 * @throws MalformedURLException
 * @throws IOException
 */
public static int getResponseCode(String urlString) throws MalformedURLException, IOException {
    URL u = new URL(urlString);
    HttpURLConnection huc = (HttpURLConnection) u.openConnection();
    huc.setRequestMethod("GET");
    huc.setRequestProperty("User-Agent",
            "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)");
    huc.connect();
    return huc.getResponseCode();
}

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 .  j av 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:com.screenslicer.common.CommonUtil.java

public static void postQuickly(String uri, String recipient, String postData) {
    HttpURLConnection conn = null;
    try {/*from   ww  w  .  ja  va  2 s  .c  o m*/
        postData = Crypto.encode(postData, recipient);
        conn = (HttpURLConnection) new URL(uri).openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json");
        byte[] bytes = postData.getBytes("utf-8");
        conn.setRequestProperty("Content-Length", String.valueOf(bytes.length));
        OutputStream os = conn.getOutputStream();
        os.write(bytes);
        conn.connect();
        Crypto.decode(IOUtils.toString(conn.getInputStream(), "utf-8"), recipient);
    } catch (Exception e) {
        Log.exception(e);
    }
}

From source file:main.java.vasolsim.common.GenericUtils.java

/**
 * Returns if a given http based address can be connected to
 *
 * @param address the address/*w  ww .  jav a2s  .co  m*/
 *
 * @return if teh connection can be made
 */
public static boolean canConnectToAddress(String address) {
    if (!isValidAddress(address))
        return false;

    try {
        HttpURLConnection connection = (HttpURLConnection) (new URL(address).openConnection());
        connection.setRequestMethod("HEAD");
        connection.connect();
        boolean success = (connection.getResponseCode() == HttpURLConnection.HTTP_OK);
        connection.disconnect();
        return success;
    } catch (Exception e) {
        return false;
    }
}

From source file:manchester.synbiochem.datacapture.SeekConnector.java

private static Status postForm(HttpURLConnection c, MultipartFormData form) throws IOException {
    c.setInstanceFollowRedirects(false);
    c.setDoOutput(true);//from www  .  j a v a  2 s.  c o  m
    c.setRequestMethod("POST");
    c.setRequestProperty("Content-Type", form.contentType());
    c.setRequestProperty("Content-Length", form.length());
    c.connect();
    try (OutputStream os = c.getOutputStream()) {
        os.write(form.content());
    }
    return fromStatusCode(c.getResponseCode());
}

From source file:com.screenslicer.common.CommonUtil.java

public static String post(String uri, String recipient, String postData) {
    HttpURLConnection conn = null;
    try {//from  w w w. ja  va2 s  .  c  om
        postData = Crypto.encode(postData, recipient);
        conn = (HttpURLConnection) new URL(uri).openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setConnectTimeout(0);
        conn.setRequestProperty("Content-Type", "application/json");
        byte[] bytes = postData.getBytes("utf-8");
        conn.setRequestProperty("Content-Length", String.valueOf(bytes.length));
        OutputStream os = conn.getOutputStream();
        os.write(bytes);
        conn.connect();
        if (conn.getResponseCode() == 205) {
            return NOT_BUSY;
        }
        if (conn.getResponseCode() == 423) {
            return BUSY;
        }
        return Crypto.decode(IOUtils.toString(conn.getInputStream(), "utf-8"), recipient);
    } catch (Exception e) {
        Log.exception(e);
    }
    return "";
}

From source file:com.webarch.common.net.http.HttpService.java

/**
 * ?Http//from  ww w.j a va  2s.com
 *
 * @param requestUrl    ?
 * @param requestMethod ?
 * @param outputJson    ?
 * @return 
 */
public static String doHttpRequest(String requestUrl, String requestMethod, String outputJson) {
    String result = null;
    try {
        StringBuffer buffer = new StringBuffer();
        URL url = new URL(requestUrl);
        HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
        httpUrlConn.setDoOutput(true);
        httpUrlConn.setDoInput(true);
        httpUrlConn.setUseCaches(false);

        httpUrlConn.setUseCaches(false);
        httpUrlConn.setRequestProperty("Accept-Charset", DEFAULT_CHARSET);
        httpUrlConn.setRequestProperty("Content-Type", "application/json;charset=" + DEFAULT_CHARSET);
        // ?GET/POST
        httpUrlConn.setRequestMethod(requestMethod);

        if ("GET".equalsIgnoreCase(requestMethod))
            httpUrlConn.connect();

        // ????
        if (null != outputJson) {
            OutputStream outputStream = httpUrlConn.getOutputStream();
            //??
            outputStream.write(outputJson.getBytes(DEFAULT_CHARSET));
            outputStream.close();
        }

        // ???
        InputStream inputStream = httpUrlConn.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, DEFAULT_CHARSET);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

        String str = null;
        while ((str = bufferedReader.readLine()) != null) {
            buffer.append(str);
        }
        result = buffer.toString();
        bufferedReader.close();
        inputStreamReader.close();
        // ?
        inputStream.close();
        httpUrlConn.disconnect();
    } catch (ConnectException ce) {
        logger.error("server connection timed out.", ce);
    } catch (Exception e) {
        logger.error("http request error:", e);
    } finally {
        return result;
    }
}

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

public static String getCtnInfo(String ncn) throws JDOMException {
    String resultStr = "";
    String logData = "";
    try {//from   w w w .j  av  a  2 s.com
        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;
}

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

/**
 * Send a file via HTTP POST with basic authentication.
 * //from ww w  . ja v a 2 s  .com
 * @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:cn.kk.exia.MangaDownloader.java

public final static HttpURLConnection getUrlConnection(final String url, final boolean post,
        final String output) throws IOException {
    int retries = 0;
    HttpURLConnection conn;
    while (true) {
        try {/* www  .j  a  va  2  s  .co m*/
            final URL urlObj = new URL(url);
            conn = (HttpURLConnection) urlObj.openConnection();
            conn.setConnectTimeout(15000);
            conn.setReadTimeout(30000);
            if (post) {
                conn.setRequestMethod("POST");
            }
            final String referer;
            final int pathIdx;
            if ((pathIdx = url.lastIndexOf('/')) > "https://".length()) {
                referer = url.substring(0, pathIdx);
            } else {
                referer = url;
            }
            conn.setRequestProperty("Referer", referer);
            final Set<String> keys = MangaDownloader.DEFAULT_CONN_HEADERS.keySet();
            for (final String k : keys) {
                final String value = MangaDownloader.DEFAULT_CONN_HEADERS.get(k);
                if (value != null) {
                    conn.setRequestProperty(k, value);
                }
            }
            // conn.setUseCaches(false);
            if (output != null) {
                conn.setDoOutput(true);
                final BufferedOutputStream out = new BufferedOutputStream(conn.getOutputStream());
                out.write(output.getBytes(MangaDownloader.CHARSET_UTF8));
                out.close();
            }
            if (MangaDownloader.appendCookies(MangaDownloader.cookie, conn)) {
                MangaDownloader.putConnectionHeader("Cookie", MangaDownloader.cookie.toString());
            }
            break;
        } catch (final Throwable e) {
            // 
            System.err.println(e.toString());
            if (retries++ > 10) {
                throw new IOException(e);
            } else {
                try {
                    Thread.sleep((60 * retries * MangaDownloader.sleepBase)
                            + ((int) Math.random() * MangaDownloader.sleepBase * 60 * retries));
                } catch (final InterruptedException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }
    return conn;
}