Java 发送POST/GET请求

GET请求:GET请求会向服务器发索取数据的请求,从而来获取信息,该请求就像数据库的select操作一样,只是用来查询一下数据,不会修改、增加数据,不会影响资源的内容,即该请求不会产生副作用。无论进行多少次操作,结果都是一样的。

post请求:POST是向服务器端发送数据的,但是该请求会改变数据的种类等资源,就像数据库的insert操作一样,会创建新的内容。几乎目前所有的提交操作都是用POST请求的。

 

javaCode:

 

[java] view plain copy

  1. /** 
  2.      * 向指定URL发送GET方法的请求 
  3.      *  
  4.      */  
  5.     public static String get(String url) {  
  6.         BufferedReader in = null;  
  7.         try {  
  8.             URL realUrl = new URL(url);  
  9.             // 打开和URL之间的连接  
  10.             URLConnection connection = realUrl.openConnection();  
  11.             // 设置通用的请求属性  
  12.             connection.setRequestProperty("accept", "*/*");  
  13.             connection.setRequestProperty("connection", "Keep-Alive");  
  14.             connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");  
  15.             connection.setConnectTimeout(5000);  
  16.             connection.setReadTimeout(5000);  
  17.             // 建立实际的连接  
  18.             connection.connect();  
  19.             // 定义 BufferedReader输入流来读取URL的响应 (可以设定相应的编码)
  20.             in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));  
  21.             StringBuffer sb = new StringBuffer();  
  22.             String line;  
  23.             while ((line = in.readLine()) != null) {  
  24.                 sb.append(line);  
  25.             }  
  26.             return sb.toString();  
  27.         } catch (Exception e) {  
  28.             LOG.error("Exception occur when send http get request!", e);  
  29.         }  
  30.         // 使用finally块来关闭输入流  
  31.         finally {  
  32.             try {  
  33.                 if (in != null) {  
  34.                     in.close();  
  35.                 }  
  36.             } catch (Exception e2) {  
  37.                 e2.printStackTrace();  
  38.             }  
  39.         }  
  40.         return null;  
  41.     }  

 

[java] view plain copy

  1. /** 
  2.      * 发送HttpPost请求 
  3.      *  
  4.      * @param strURL 
  5.      *            服务地址 
  6.      * @param params 
  7.      *  
  8.      * @return 成功:返回json字符串<br/> 
  9.      */  
  10.     public static String jsonPost(String strURL, Map<String, String> params) {  
  11.       try {  
                URL url = new URL(strURL);// 创建连接  
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();  
                connection.setDoOutput(true);  
                connection.setDoInput(true);  
                connection.setUseCaches(false);  
                connection.setInstanceFollowRedirects(true);  
                connection.setRequestMethod("POST"); // 设置请求方式  
                connection.setRequestProperty("Accept", "application/x-www-form-urlencoded"); // 设置接收数据的格式  
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 设置发送数据的格式  
                connection.connect();
                StringBuffer param = new StringBuffer();  
                for (String key : params.keySet()) {  
                    param.append("&");  
                    param.append(key).append("=").append(URLEncoder.encode(params.get(key), "utf-8"));  
                }
                DataOutputStream out = new DataOutputStream(connection.getOutputStream());  
                // DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写到流里面  
                out.writeBytes(param.toString());  
                //流用完记得关  
                out.flush();  
                out.close();  
                //获取响应  
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));  
                String line,result="";  
                while ((line = reader.readLine()) != null){  
                   result += line;
                }  
                reader.close();  
                //该干的都干完了,记得把连接断了  
                connection.disconnect();

                return result;
           
            } catch (IOException e) {
                e.printStackTrace();
                return "error";
            } 
  12.   } 
  13.  /**
         *
         * <p>Title: doPost</p>  
         * <p>Description:post请求 </p>  
         * @param url
         * @param json
         * @return
         */
        public static JSONObject doPost(String url,Object json){
            HttpClient client = HttpClientBuilder.create().build();
                HttpPost post = new HttpPost(url);
                JSONObject response = null;
                try {
                    StringEntity s = new StringEntity(json.toString());
                    s.setContentEncoding("UTF-8");
                    s.setContentType("application/json");//发送json数据需要设置contentType
                    post.setEntity(s);
                    HttpResponse res = client.execute(post);
                    if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                        String result = EntityUtils.toString(res.getEntity());// 返回json格式:
                        response = JSONObject.fromObject(result);
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                return response;
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值