重點在這一句: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;}