读取配置文件的URL,使用httpClient发送Post和Get请求,实现查询快递物流和智能机器人对话

时间:2023-03-09 13:11:12
读取配置文件的URL,使用httpClient发送Post和Get请求,实现查询快递物流和智能机器人对话

1、主要jar包:

httpclient-4.3.5.jar   httpcore-4.3.2.jar

2、目录结构如图所示:

读取配置文件的URL,使用httpClient发送Post和Get请求,实现查询快递物流和智能机器人对话

3、url.properties文件如下:

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

读取配置文件的URL,使用httpClient发送Post和Get请求,实现查询快递物流和智能机器人对话

4、主要代码 GetAndPost.java:

 /**
*
*/
package getandpost; import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties; import org.apache.commons.collections.map.LinkedMap;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.util.URIUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
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.google.gson.Gson; /**
* @author hy
* @date 2019-02-26 14:02:56
*
*/
public class GetAndPost { public static void main(String[] args) throws Exception { /**
* 快递公司编码: 申通="shentong" EMS="ems" 顺丰="shunfeng" 圆通="yuantong"
* 中通="zhongtong" 韵达="yunda" 天天="tiantian" 汇通="huitongkuaidi"
* 全峰="quanfengkuaidi" 德邦="debangwuliu" 宅急送="zhaijisong"
*/
doGet(paraUtil("yunda", "3101775486667"), "");
doPost("2581f443bf364fd8a927fe87832e3d33", "晚上吃啥?", "hyblogs", "");
} public static String paraUtil(String param1, String param2) {
/*
* 接收String ,转为url
*/
HashMap<String, String> Map = new HashMap<>();
String para = null;
Map.put("type", param1);
Map.put("postid", param2);
StringBuffer parameters = new StringBuffer();
for (Entry<String, String> mp : Map.entrySet()) {
parameters.append(mp.getKey() + "=" + mp.getValue() + "&");
}
para = "&"
+ parameters.toString().substring(0,
parameters.toString().length() - 1);
return para; } /* 发送GET的工具方法 */
public static String doGet(String content, String encode) throws Exception {
if (encode == null || "".equals(encode)) {
encode = "utf-8";
}
String geturl = getConfig().get("geturl");
String response = null;
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(geturl);
client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,encode);
System.out.println(method.getName());
try {
if (StringUtils.isNotBlank(content))
method.setQueryString(URIUtil.encodeQuery(content));
client.executeMethod(method);
if (method.getStatusCode() == HttpStatus.SC_OK) // 等于200表示请求成功
{
response = method.getResponseBodyAsString();
}
} catch (URIException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
method.releaseConnection();
}
System.out.println(response);
return response;
} /* 发送Post请求的工具方法 */
public static String doPost(String key, String info, String userid,
String encode) throws Exception {
if (encode == null || "".equals(encode)) {
encode = "utf-8";
}
String posturl = getConfig().get("posturl");
String response = null;
try {
// 第一步:创建HttpClient对象
CloseableHttpClient client = HttpClients.createDefault();
// 第二步:创建httpPost对象
HttpPost httpPost = new HttpPost(posturl);
System.out.println(HttpPost.METHOD_NAME);
LinkedMap map = new LinkedMap();
map.put("key", key);
map.put("info", info);
map.put("userid", userid);
Gson gson = new Gson();
String json = gson.toJson(map);
StringEntity entity = new StringEntity(json, encode);// 解决中文乱码问题
entity.setContentEncoding(encode);
entity.setContentType("application/json");
httpPost.setEntity(entity);
HttpResponse resp = client.execute(httpPost);
System.out.println(resp);
if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) // 等于200表示请求成功
{
HttpEntity he = resp.getEntity();
response = EntityUtils.toString(he, "UTF-8");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(response);
return response;
} public static Map<String, String> getConfig() throws Exception {
HashMap<String, String> map = new HashMap<String, String>();
Properties property = new Properties();
try {
property = PropertiesUtil.loadProperties("config/url.properties");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
map.put("geturl", property.getProperty("geturl"));
map.put("posturl", property.getProperty("posturl"));
return map;
}
}

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

 package getandpost;

 import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties; public class PropertiesUtil {
public static Properties loadProperties(String... profilepath) throws IOException {
Properties prop = new Properties();
//传入的多个配置文件中,如有相同的属性名,以最后的配置文件属性值为准(会覆盖掉前面的属性值)
for (String path : profilepath) {
try {
prop.load(PropertiesUtil.class.getClassLoader().getResourceAsStream(path));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return prop;
}
}

运行结果:

读取配置文件的URL,使用httpClient发送Post和Get请求,实现查询快递物流和智能机器人对话