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

posted @ 2018-03-22 11:28  congcongdi  阅读(3117)  评论(0编辑  收藏  举报