java的Http的PUT請求

來源:互聯網
上載者:User


重點在這一句:httpurlconnection.setRequestMethod("PUT");
如果想改成post請求,就該成httpurlconnection.setRequestMethod("POST");就可以了。



public static String httpPut(String urlPath, String data, String charSet, String[] header){String result = null;URL url = null;HttpURLConnection httpurlconnection = null;try{url = new URL(urlPath);httpurlconnection = (HttpURLConnection) url.openConnection();httpurlconnection.setDoInput(true);httpurlconnection.setDoOutput(true);httpurlconnection.setConnectTimeout(2000000);// 設定串連主機逾時(單位:毫秒)httpurlconnection.setReadTimeout(2000000);// 設定從主機讀取資料逾時(單位:毫秒)if (header != null){for (int i = 0; i < header.length; i++){String[] content = header[i].split(":");httpurlconnection.setRequestProperty(content[0], content[1]);}}httpurlconnection.setRequestMethod("PUT");httpurlconnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");if (StringUtils.isNotBlank(data)){httpurlconnection.getOutputStream().write(data.getBytes("UTF-8"));}httpurlconnection.getOutputStream().flush();httpurlconnection.getOutputStream().close();int code = httpurlconnection.getResponseCode();if (code == 200){DataInputStream in = new DataInputStream(httpurlconnection.getInputStream());int len = in.available();byte[] by = new byte[len];in.readFully(by);if (StringUtils.isNotBlank(charSet)){result = new String(by, Charset.forName(charSet));} else{result = new String(by);}in.close();} else{log.error("請求地址:" + urlPath + "返回狀態異常,異常號為:" + code);}} catch (Exception e){log.error("訪問url地址:" + urlPath + "發生異常", e);} finally{url = null;if (httpurlconnection != null){httpurlconnection.disconnect();}}return result;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.