public static String sendMsg(String urlpath,String sendmsg) throws IOException{ String result=""; URL url = new URL(urlpath); //創建url連接 HttpURLConnection connect = (HttpURLConnection) url.openConnection(); //打開連接 connect.setDoOutput(true); connect.setDoInput(true); connect.setRequestMethod("POST"); connect.setUseCaches(false); //Post 請求不能使用緩存 connect.connect(); OutputStreamWriter osw = new OutputStreamWriter(connect.getOutputStream()); //此處需要注意編碼方式,要跟接收平台的編碼保持一致,此處默認是GBK osw.write(sendmsg); osw.flush(); BufferedReader reader = new BufferedReader(new InputStreamReader(connect.getInputStream(), "utf-8")); StringBuffer buffer = new StringBuffer(); String line = ""; while ((line = reader.readLine()) != null) { buffer.append(line); } result = buffer.toString(); reader.close(); osw.close(); connect.disconnect(); return result; }
或者:
public static String httpPost(String url,String content)throws Exception{ CloseableHttpClient closeableHttpClient=HttpClients.createDefault(); HttpPost httpPost=new HttpPost(url); StringEntity se=new StringEntity(content); httpPost.setEntity(se); CloseableHttpResponse chr=closeableHttpClient.execute(httpPost); return EntityUtils.toString(chr.getEntity()); }
此方法需要一些jar包的支持