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:

 /**
*
*/
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请求,实现查询快递物流和智能机器人对话的更多相关文章

  1. HttpClient发送get,post接口请求

    HttpClient发送get post接口请求/*  * post  * @param url POST地址 * @param data POST数据NameValuePair[] * @retur ...

  2. Android笔记---使用HttpClient发送POST和GET请求

    在Android上发送 HTTP 请求的方式一般有两种, HttpURLConnection 和 HttpClient,关于HttpURLConnection的使用方法能够參考HTTP之利用HttpU ...

  3. Java实现HttpClient发送GET、POST请求(https、http)

    1.引入相关依赖包 jar包下载:httpcore4.5.5.jar    fastjson-1.2.47.jar maven: <dependency> <groupId>o ...

  4. java使用HttpClient 发送get、pot请求

    package eidolon.messageback.PostUtil; import java.io.BufferedReader; import java.io.IOException; imp ...

  5. java apache commons HttpClient发送get和post请求的学习整理(转)

    文章转自:http://blog.csdn.net/ambitiontan/archive/2006/01/06/572171.aspx HttpClient 是我最近想研究的东西,以前想过的一些应用 ...

  6. 使用httpclient发送get或post请求

    HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的.最新的.功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建 ...

  7. HttpClient 发送 HTTP、HTTPS 请求的简单封装

    import org.apache.commons.io.IOUtils; import org.apache.http.HttpEntity; import org.apache.http.Http ...

  8. [java,2018-01-16] HttpClient发送、接收 json 请求

    最近需要用到许多在后台发送http请求的功能,可能需要发送json和xml类型的数据. 就抽取出来写了一个帮助类: 首先判断发送的数据类型是json还是xml: import org.dom4j.Do ...

  9. HttpClient发送Get和Post请求

    package JanGin.httpClient.demo; import java.io.IOException; import java.io.UnsupportedEncodingExcept ...

随机推荐

  1. MySQL隐形索引简介

    不可见索引允许您将索引标记为查询优化器不可用.MySQL维护不可见索引,并在与索引关联的列中的数据发生更改时使其保持最新. 默认情况下,索引是可见的.要使它们不可见,您必须在创建时或使用ALTER T ...

  2. webservice安全性浅谈

    原文地址:http://www.cnblogs.com/chhuic/archive/2009/11/19/1606109.html 做项目时,经常会用到WebService来通讯,但WebServi ...

  3. Win7 user profile cant logon

    1.local user:testlb1 1234@cat can login safe model 1.重新启动计算机开机时连续点击F8,选择进入安全模式.2.开始-在搜索栏中输入services. ...

  4. NHibernate出现could not execute query问题

    今天在调试代码时工程总报错,提示could not execute query xxxxxxxxxxxxxxxxxxxxxxxxxxx 找了很久,最终同事发现是数据库连接配置文件的问题. <hi ...

  5. [LOJ 6029]「雅礼集训 2017 Day1」市场

    [LOJ 6029] 「雅礼集训 2017 Day1」市场 题意 给定一个长度为 \(n\) 的数列(从 \(0\) 开始标号), 要求执行 \(q\) 次操作, 每次操作为如下四种操作之一: 1 l ...

  6. JSR规范

    JSR是JavaSpecification Requests的缩写,意思是Java 规范提案.是指向JCP(Java Community Process)提出新增一个标准化技术规范的正式请求.任何人都 ...

  7. react的新手基础知识笔记

    <!DOCTYPE html> <html> <head> <script src="../build/react.js">< ...

  8. 【Nginx】开启 gzip和缓存

    Nginx 开启 gzip和缓存 时间:2016-09-23 16:42:37 nginx 是一个高性能的 Web 服务器,之前也写过一些关于 nginx 的文章.为了提高博客的响应速度,可以从设置 ...

  9. BZOJ 1834 网络扩容 最大流+最小费用流

    题目链接: https://www.lydsy.com/JudgeOnline/problem.php?id=1834 题目大意: 给定一张有向图,每条边都有一个容量C和一个扩容费用W.这里扩容费用是 ...

  10. Codeforces Round #503 Div. 2

    时间相对来说还是比较合适的,正好放假就可以打一打啦. A. New Building for SIS:http://codeforces.com/contest/1020/problem/A 题意概述 ...