读取配置文件的URL,使用httpClient发送Post和Ge…

2019-03-01 10:13:23来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

1、主要jar包:

httpclient-4.3.5.jar   httpcore-4.3.2.jar

2、目录结构如图所示:

3、url.properties文件如下:

geturl=http://www.kuaidi100.com/query
posturl=http://www.tuling123.com/openapi/api

4、主要代码 GetAndPost.java:

  1 /**
  2  * 
  3  */
  4 package getandpost;
  5 
  6 import java.io.FileNotFoundException;
  7 import java.io.IOException;
  8 import java.util.HashMap;
  9 import java.util.Map;
 10 import java.util.Map.Entry;
 11 import java.util.Properties;
 12 
 13 import org.apache.commons.collections.map.LinkedMap;
 14 import org.apache.commons.httpclient.HttpClient;
 15 import org.apache.commons.httpclient.HttpMethod;
 16 import org.apache.commons.httpclient.HttpStatus;
 17 import org.apache.commons.httpclient.URIException;
 18 import org.apache.commons.httpclient.methods.GetMethod;
 19 import org.apache.commons.httpclient.params.HttpMethodParams;
 20 import org.apache.commons.httpclient.util.URIUtil;
 21 import org.apache.commons.lang.StringUtils;
 22 import org.apache.http.HttpEntity;
 23 import org.apache.http.HttpResponse;
 24 import org.apache.http.client.ClientProtocolException;
 25 import org.apache.http.client.methods.HttpPost;
 26 import org.apache.http.entity.StringEntity;
 27 import org.apache.http.impl.client.CloseableHttpClient;
 28 import org.apache.http.impl.client.HttpClients;
 29 import org.apache.http.util.EntityUtils;
 30 
 31 import com.google.gson.Gson;
 32 
 33 /**
 34  * @author hy
 35  * @date 2019-02-26 14:02:56
 36  * 
 37  */
 38 public class GetAndPost {
 39 
 40     public static void main(String[] args) throws Exception {
 41 
 42         /**
 43          * 快递公司编码: 申通="shentong" EMS="ems" 顺丰="shunfeng" 圆通="yuantong"
 44          * 中通="zhongtong" 韵达="yunda" 天天="tiantian" 汇通="huitongkuaidi"
 45          * 全峰="quanfengkuaidi" 德邦="debangwuliu" 宅急送="zhaijisong"
 46          */
 47         doGet(paraUtil("yunda", "3101775486667"), "");
 48         doPost("2581f443bf364fd8a927fe87832e3d33", "晚上吃啥?", "hyblogs", "");
 49     }
 50 
 51     public static String paraUtil(String param1, String param2) {
 52         /*
 53          * 接收String ,转为url
 54          */
 55         HashMap<String, String> Map = new HashMap<>();
 56         String para = null;
 57         Map.put("type", param1);
 58         Map.put("postid", param2);
 59         StringBuffer parameters = new StringBuffer();
 60         for (Entry<String, String> mp : Map.entrySet()) {
 61             parameters.append(mp.getKey() + "=" + mp.getValue() + "&");
 62         }
 63         para = "&"
 64                 + parameters.toString().substring(0,
 65                         parameters.toString().length() - 1);
 66         return para;
 67 
 68     }
 69 
 70     /* 发送GET的工具方法 */
 71     public static String doGet(String content, String encode) throws Exception {
 72         if (encode == null || "".equals(encode)) {
 73             encode = "utf-8";
 74         }
 75         String geturl = getConfig().get("geturl");
 76         String response = null;
 77         HttpClient client = new HttpClient();
 78         HttpMethod method = new GetMethod(geturl);
 79         client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,encode);
 80         System.out.println(method.getName());
 81         try {
 82             if (StringUtils.isNotBlank(content))
 83                 method.setQueryString(URIUtil.encodeQuery(content));
 84                 client.executeMethod(method);
 85             if (method.getStatusCode() == HttpStatus.SC_OK) // 等于200表示请求成功
 86             {
 87                 response = method.getResponseBodyAsString();
 88             }
 89         } catch (URIException e) {
 90             e.printStackTrace();
 91         } catch (IOException e) {
 92             e.printStackTrace();
 93         } finally {
 94             method.releaseConnection();
 95         }
 96         System.out.println(response);
 97         return response;
 98     }
 99 
100     /* 发送Post请求的工具方法 */
101     public static String doPost(String key, String info, String userid,
102             String encode) throws Exception {
103         if (encode == null || "".equals(encode)) {
104             encode = "utf-8";
105         }
106         String posturl = getConfig().get("posturl");
107         String response = null;
108         try {
109             // 第一步:创建HttpClient对象
110             CloseableHttpClient client = HttpClients.createDefault();
111             // 第二步:创建httpPost对象
112             HttpPost httpPost = new HttpPost(posturl);
113             System.out.println(HttpPost.METHOD_NAME);
114             LinkedMap map = new LinkedMap();
115             map.put("key", key);
116             map.put("info", info);
117             map.put("userid", userid);
118             Gson gson = new Gson();
119             String json = gson.toJson(map);
120             StringEntity entity = new StringEntity(json, encode);// 解决中文乱码问题
121             entity.setContentEncoding(encode);
122             entity.setContentType("application/json");
123             httpPost.setEntity(entity);
124             HttpResponse resp = client.execute(httpPost);
125             System.out.println(resp);
126             if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) // 等于200表示请求成功
127             {
128                 HttpEntity he = resp.getEntity();
129                 response = EntityUtils.toString(he, "UTF-8");
130             }
131         } catch (ClientProtocolException e) {
132             e.printStackTrace();
133         } catch (IOException e) {
134             e.printStackTrace();
135         }
136         System.out.println(response);
137         return response;
138     }
139 
140     public static Map<String, String> getConfig() throws Exception {
141         HashMap<String, String> map = new HashMap<String, String>();
142         Properties property = new Properties();
143         try {
144             property = PropertiesUtil.loadProperties("config/url.properties");
145         } catch (FileNotFoundException e) {
146             e.printStackTrace();
147         } catch (IOException e) {
148             e.printStackTrace();
149         }
150         map.put("geturl", property.getProperty("geturl"));
151         map.put("posturl", property.getProperty("posturl"));
152         return map;
153     }
154 }

5、读取配置文件中的url,PropertiesUtil.java:

 1 package getandpost;
 2 
 3 import java.io.FileNotFoundException;
 4 import java.io.IOException;
 5 import java.util.Properties;
 6 
 7 public class PropertiesUtil {
 8     public static Properties loadProperties(String... profilepath) throws IOException {
 9         Properties prop = new Properties();
10         //传入的多个配置文件中,如有相同的属性名,以最后的配置文件属性值为准(会覆盖掉前面的属性值)
11         for (String path : profilepath) {
12             try {
13                 prop.load(PropertiesUtil.class.getClassLoader().getResourceAsStream(path));
14             } catch (FileNotFoundException e) {
15                 e.printStackTrace();
16             } catch (IOException e) {
17                 e.printStackTrace();
18             }
19         }
20         return prop;
21     }
22 }

运行结果:

 


原文链接:https://www.cnblogs.com/hyblogs/p/10451006.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:微服务---负载均衡Robbin

下一篇:JDK,JRE,JVM三者关系