java中post delete get请求

/**
 * get请求 (返回值为JSON)
 * @return
 * @throws IOException 
 * @throws IOException 
 */
public static Map<String,Object> sendMethod(String requestUrl){
   JSONObject json=new JSONObject();
   try {
        URL url = new URL(requestUrl);
        HttpURLConnection connt = (HttpURLConnection)url.openConnection();
        String strMessage=connt.getResponseMessage();
        if(strMessage.compareTo("Not Found")!=0){
           BufferedReader in = new BufferedReader(new InputStreamReader(connt.getInputStream(),"utf-8"));
            String inputLine = null; 
            while ( (inputLine = in.readLine()) != null) {
               json=JSONObject.parseObject(inputLine);
            }  
            in.close();  
        }else{
           json.put("Code", -1);
           json.put("Message", "无法连接网络");
        }
   } catch (Exception e) {
      e.printStackTrace();
   }
       return json;
}

/**
 * body提交方式
 * post方法提交
 * @param requestUrl
 * @return
 */
public static JSONObject sendMethodPost(String requestUrl,Map<String, String> params){
   JSONObject json=new JSONObject();
   try {
           URL url = new URL(requestUrl);// 创建连接  
           HttpURLConnection connection = (HttpURLConnection) url.openConnection();  
           connection.setDoOutput(true);  
           connection.setDoInput(true);  
           connection.setUseCaches(false);  
           connection.setInstanceFollowRedirects(true);  
           connection.setRequestMethod("POST"); // 设置请求方式  
           connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式  
           connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式  
           connection.connect();  
           OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码  
           out.append(params.toString());  
           out.flush();  
           out.close();  
 
           int code = connection.getResponseCode();  
           InputStream is = null;  
           if (code == 200) {  
               is = connection.getInputStream();  
           } else {  
               is = connection.getErrorStream();  
           }  
 
           // 读取响应  
           int length = (int) connection.getContentLength();// 获取长度  
           if (length != -1) {  
               byte[] data = new byte[length];  
               byte[] temp = new byte[512];  
               int readLen = 0;  
               int destPos = 0;  
               while ((readLen = is.read(temp)) > 0) {  
                   System.arraycopy(temp, 0, data, destPos, readLen);  
                   destPos += readLen;  
               }  
               String result = new String(data, "UTF-8"); // utf-8编码  
               System.out.println("result:"+result);
           }  
 
       } catch (IOException e) {  
           log.error("Exception occur when send http post request!", e);
       }  
       return json; // 自定义错误信息  
}
/**
 * PUT方式提交
 * @param dst_ip
 */
public static Map<String,Object> doPut(String strUrl,String param){ 
      CloseableHttpClient httpclient = HttpClients.createDefault();
      StringBuffer jsonString= new StringBuffer();
      JSONObject json = new JSONObject();
       try {
          final HttpPut put=new HttpPut(strUrl);
          put.setEntity(new StringEntity(param,"UTF-8")); 
           CloseableHttpResponse response1= httpclient.execute(put); 
           try {
               HttpEntity entity1 = response1.getEntity();
               BufferedReader br = new BufferedReader(new InputStreamReader(entity1.getContent(),"utf-8")); 
               String line;
               while ((line = br.readLine()) != null) {
                       jsonString.append(line);
               }  
               EntityUtils.consume(entity1);
           } finally {
               response1.close();
           }
           json=JSONObject.parseObject(jsonString.toString());
       }catch(Exception e){
           e.printStackTrace();
       }
       return json;
}
/**
 * DELETE方式提交
 * @param dst_ip
 */
public static String doDelete(String urlToRead) throws Exception {
    URL url = new URL(urlToRead);
    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
    httpCon.setDoOutput(true);
    httpCon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded" );
    httpCon.setRequestMethod("DELETE");
    httpCon.connect();
    httpCon.disconnect(); 
    // 获取返回的数据  
       BufferedReader in = new BufferedReader(new InputStreamReader(httpCon.getInputStream(),"utf-8"));  
       String line = null;  
       StringBuffer content = new StringBuffer();  
       while ((line = in.readLine()) != null) {
           // line 为返回值,这就可以判断是否成功  
           content.append(line);  
       }  
       in.close();  
       return content.toString();  
   }

 /**
    * 函数功能描述:UTC时间转本地时间格式
    * @param utcTime UTC时间
    * @param utcTimePatten UTC时间格式
    * @param localTimePatten   本地时间格式
    * @return 本地时间格式的时间
    * eg:utc2Local("2017-06-14 09:37:50.788+08:00", "yyyy-MM-dd HH:mm:ss.SSSXXX", "yyyy-MM-dd HH:mm:ss.SSS")
    */
   public static String utc2Local(String utcTime, String utcTimePatten, String localTimePatten) {
       SimpleDateFormat utcFormater = new SimpleDateFormat(utcTimePatten);
       utcFormater.setTimeZone(TimeZone.getTimeZone("UTC"));//时区定义并进行时间获取
       Date gpsUTCDate = null;
       try {
           gpsUTCDate = utcFormater.parse(utcTime);
       } catch (Exception e) {
           e.printStackTrace();
           return utcTime;
       }
       SimpleDateFormat localFormater = new SimpleDateFormat(localTimePatten);
       localFormater.setTimeZone(TimeZone.getDefault());
       String localTime = localFormater.format(gpsUTCDate.getTime());
       return localTime;
   }

   /**
    * 表单提交方式
    * @method: requestSend
    * @param: [url, map]
    * @date: 2019/4/29 17:33
    * @return: 
    * @version: v1.0
    */
   public static String requestSend(String url, Map<String,String> map) {
       HttpResponse response = null;
       HttpClient client = null;
       HttpPost httpPost = new HttpPost(url);
       try {
           List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
           for(String key : map.keySet()) {
               list.add(new BasicNameValuePair(key,map.get(key).toString()));
           }
           UrlEncodedFormEntity uefe = new UrlEncodedFormEntity(list,"utf-8");
           uefe.setContentType("application/x-www-form-urlencoded");

           httpPost.setEntity(uefe);
           httpPost.setHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");
           client = HttpClients.createDefault();
           response = client.execute(httpPost);
           HttpEntity entity = response.getEntity();
           String res = EntityUtils.toString(entity, "utf-8");
           return res;
       }catch (Exception e) {
           e.printStackTrace();
           return null;
       }finally {
           httpPost.releaseConnection();
       }
   }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值