get post HTTP 请求

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.noahgroup.paas.cicd.dao.model.message.generator.Apollo;
import com.noahgroup.paas.cicd.dao.model.message.generator.NamespaceItem;

import net.sf.json.JSONObject;

public class ApolloUtil {
    
     public static String getApollo(String url, String token) {
            String result = "";
            BufferedReader in = null;
            try {
                URL realUrl = new URL(url);
                // 打开和URL之间的连接
                URLConnection connection = realUrl.openConnection();
                connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
                connection.setRequestProperty("Authorization", token);
                connection.connect();
                in = new BufferedReader(new InputStreamReader(
                        connection.getInputStream()));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
            } catch (Exception e) {
                System.out.println("发送GET请求出现异常!" + e);
                e.printStackTrace();
            }
            // 使用finally块来关闭输入流
            finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
            return result;
        }
        @SuppressWarnings("unchecked")
        @JsonIgnoreProperties(ignoreUnknown = true)
        public static Apollo jsonToApollo(String json) {
             Apollo apollo = new Apollo();
            ObjectMapper mapper = new ObjectMapper();
            try {
                Map<String, Object> map = new HashMap<String, Object>();
                map = mapper.readValue(json, new TypeReference<Map<String, Object>>() {
                });
                
                List<Map<String, Object>> stages = (List<Map<String, Object>>) map.get("items");
                List<NamespaceItem> itemList = new ArrayList<NamespaceItem>();
                for (Map<String, Object> stage : stages) {
                    NamespaceItem namespace = mapper.readValue(mapper.writeValueAsString(stage), NamespaceItem.class);
                    itemList.add(namespace);
                }
                apollo.setToken((String)map.get("token")); 
                apollo.setAppId((String)map.get("appId")); 
                apollo.setEnv((String)map.get("env")); 
                apollo.setClusterName((String)map.get("clusterName")); 
                apollo.setNamespaceName((String)map.get("namespaceName")); 
                apollo.setComment((String)map.get("comment")); 
                apollo.setFormat((String)map.get("format")); 
                String str=String.valueOf(map.get("isPublic"));
                if("true".equalsIgnoreCase(str)){
                    apollo.setIsPublic("公有");
                }else {
                    apollo.setIsPublic("私有");
                }
                apollo.setDataChangeCreatedBy((String)map.get("dataChangeCreatedBy")); 
                apollo.setDataChangeLastModifiedBy((String)map.get("dataChangeLastModifiedBy")); 
                apollo.setDataChangeCreatedTime((String)map.get("dataChangeCreatedTime")); 
                apollo.setDataChangeLastModifiedTime((String)map.get("dataChangeLastModifiedTime")); 
                apollo.setItems(itemList);
            } catch (JsonGenerationException e) {
                e.printStackTrace();
            } catch (JsonMappingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return apollo;
        }
        
        public static String postApollo(String string, String token, JSONObject jsonParam) {
             
              // 获取连接客户端工具
                CloseableHttpClient httpClient = HttpClients.createDefault();

                String entityStr = null;
                CloseableHttpResponse response = null;

                try {

                    // 创建POST请求对象
                    HttpPost httpPost = new HttpPost(string);

                  StringEntity entity = new StringEntity(jsonParam.toString(),"utf-8");//解决中文乱码问题
                  httpPost.setEntity(entity);

                 // 添加请求头信息
                    httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
                    httpPost.addHeader("Authorization", token);
                      
                    // 执行请求
                    response = httpClient.execute(httpPost);
                    // 获得响应的实体对象
                    
                    HttpEntity entity2 = response.getEntity();
                    // 使用Apache提供的工具类进行转换成字符串
                    entityStr = EntityUtils.toString(entity2, "UTF-8");


                } catch (ClientProtocolException e) {
                    System.err.println("Http协议出现问题");
                    e.printStackTrace();
                } catch (ParseException e) {
                    System.err.println("解析错误");
                    e.printStackTrace();
                } catch (IOException e) {
                    System.err.println("IO异常");
                    e.printStackTrace();
                } finally {
                    // 释放连接
                    if (null != response) {
                        try {
                            response.close();
                            httpClient.close();
                        } catch (IOException e) {
                            System.err.println("释放连接出错");
                            e.printStackTrace();
                        }
                    }
                }
             
         return entityStr;

         }

猜你喜欢

转载自blog.csdn.net/stone_tomcate/article/details/81669725