http發送post請求


        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包的支持

https://download.csdn.net/download/qq_35792159/10301873


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM