接口开发中的httpget和httppost的应用
2018-03-20 20:27
253 查看
参加新工作一周有余,领导安排任务写几个接口开发。What????之前没写过,脑子一片懵逼,看着文档看了两天,迟迟进入不了状态,百度一顿,终于明白了领导安排的任务。
废话不多说,上个文档先~~~~
文档内容如下:
简介:API 的access_token获取,有效期通过expires_in来传达。请求方在刷新access_token过程中,统一认证平台会保证新旧access_token在5分钟内都可用。这里的access_token与网页授权的access_token不同。接口:http://xxx.com/api/oauth20/accesstoken/client?grant_type=client_credentials&client_id=CLIENT_ID&client_secret =CLIENT_SECRET
GET请求参数:
返回参数:
{"access_token":"access_token","expires_in":7200}
参数说明:
其实也不难,之前没写过,问问同事,终于懂了需求,就是写一个java类作为一个工具类,工具类往http://xxx.com/api/oauth20/accesstoken/client?grant_type=client_credentials&client_id=CLIENT_ID&client_secret =CLIENT_SECRET 发送请求,会返回一个json对象,将json对象获取。
百度了一下,明白了需要HttpClient、Httppost或者Httpget类进行处理,具体代码如下:
需要注意的是,get和post请求方式不一样的地方是post需要创建简单名称值对节点类型的集合,然后将集合设置成post提交的参数,用"UTF-8"方式提交。
对于返回的结果,可以预先用谷歌的postman插件进行测试,针对不同的结果用JsonParser进行解析成jsonobject或者jsonarray。
当然,实际情况中POST请求的还有可能是Json格式的参数,此处需要JSONObject进行封装,同时针对返回结果,也可以封装成一个javaBean,代码如下:public class CustomerRegisterUtils {
// 客户注册
public static ResultCustomerRegister registerCustomer(String access_token, String mobile, String wx_open_id, String wx_union_id){
// 设置json格式的参数
JSONObject params = new JSONObject();
params.put("mobile", mobile);
params.put("wx_open_id", wx_open_id);
params.put("wx_union_id", wx_union_id);
// 获取接口
Properties pro = PropertyUtil.getPropertys("access_token.properties");
String apiurl = (String) pro.get("CUSTOMER_REGISTER_URL");
// 拼接url
String url = String.format("%s?access_token=%s", apiurl, access_token);
// 创建httpclient对象
HttpClient client = new DefaultHttpClient();
// post请求方式
HttpPost post = new HttpPost(url);
// 返回结果
ResultCustomerRegister registerResult = null;
// 设置参数
try {
StringEntity stringEntity = new StringEntity(params.toString(), "UTF-8");
//发送json数据需要设置contentType
stringEntity.setContentType("application/json");
post.setEntity(stringEntity);
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
try
{
HttpResponse res = client.execute(post);
// 响应内容
HttpEntity entity = res.getEntity();
String responseContent = EntityUtils.toString(entity, "UTF-8");
// 将结果转化为bean对象
JSONObject object = JSONObject.fromObject(responseContent);
registerResult = (ResultCustomerRegister) JSONObject.toBean(object,ResultCustomerRegister.class);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
// 关闭连接 ,释放资源
client.getConnectionManager().shutdown();
return registerResult;
}
}
}
废话不多说,上个文档先~~~~
文档内容如下:
简介:API 的access_token获取,有效期通过expires_in来传达。请求方在刷新access_token过程中,统一认证平台会保证新旧access_token在5分钟内都可用。这里的access_token与网页授权的access_token不同。接口:http://xxx.com/api/oauth20/accesstoken/client?grant_type=client_credentials&client_id=CLIENT_ID&client_secret =CLIENT_SECRET
GET请求参数:
参数名 | 是否必选 | 类型 | 说明 |
grant_type | 必选 | String | 获取access_token填写client_credentials |
client_id | 必选 | String | 接入应用的唯一标识 |
client_secret | 必选 | String | 接入应用的密钥 |
{"access_token":"access_token","expires_in":7200}
参数说明:
参数名 | 是否必选 | 类型 | 说明 |
access_token | 必选 | String | 凭证 |
expires_in | 必选 | Int | 凭证有效期,单位:秒 |
百度了一下,明白了需要HttpClient、Httppost或者Httpget类进行处理,具体代码如下:
1,get请求方式
package XXXX; import java.util.Properties; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import xxx.tools.PropertyUtil; public class AccessTokenGetUtils { // 获取acess_token public static String getToken( String client_id, String client_secret){ // 读取配置文件, 获取接口 Properties pro = PropertyUtil.getPropertys("access_token.properties"); String apiurl = (String) pro.get("GET_TOKEN_URL"); String url = String.format("%s?grant_type=client_credentials&client_id=%s&client_sceret=%s", apiurl, client_id, client_secret); HttpClient client = new DefaultHttpClient(); // get请求 HttpGet get = new HttpGet(url); // 初始化解析json格式的对象 JsonParser jsonparer = new JsonParser(); String result = null; try { HttpResponse res = client.execute(get); // 响应内容 String responseContent = null; HttpEntity entity = res.getEntity(); responseContent = EntityUtils.toString(entity, "UTF-8"); System.out.println(responseContent); // 将json字符串转换为json对象 JsonObject json = jsonparer.parse(responseContent).getAsJsonObject(); if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { //错误时返回格式文档未说明........ if (json.get("errcode") != null) {// 错误时会返回错误码等信息,{"errcode":40013,"errmsg":"invalid client_id"} ,一般根据接口的返回信息作出判断 result = json.get("errcode").getAsString(); } else {// 正常情况下{"access_token":"529f5643-71fc-3236-93c4-b8e1e102f097","expire_in":7200} result = json.get("access_token").getAsString(); } } } catch (Exception e) { e.printStackTrace(); } finally { // 关闭连接 ,释放资源 client.getConnectionManager().shutdown(); return result; } } }
2.1post方式,传普通数据
public class AccessTokenGetUtilsP { // 获取acess_token public static String getToken( String client_id, String client_secret){ // 创建简单名称值对节点类型的集合 List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(); urlParameters.add(new BasicNameValuePair("client_id", client_id)); urlParameters.add(new BasicNameValuePair("client_secret", client_secret)); // 获取接口 Properties pro = PropertyUtil.getPropertys("access_token.properties"); String apiurl = (String) pro.get("GET_TOKEN_URL"); String url = String.format("%s?grant_type=client_credentials", apiurl); // 创建httpclient对象 HttpClient client = new DefaultHttpClient(); // post请求方式 HttpPost post = new HttpPost(url); // 设置参数 try { post.setEntity(new UrlEncodedFormEntity(urlParameters, "UTF-8")); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } // 初始化解析json格式的对象 JsonParser jsonparer = new JsonParser(); String result = null; try { HttpResponse res = client.execute(post); // 响应内容 String responseContent = null; HttpEntity entity = res.getEntity(); responseContent = EntityUtils.toString(entity, "UTF-8"); // System.out.println(responseContent); // return responseContent; // 将json字符串转换为json对象 JsonObject json = jsonparer.parse(responseContent).getAsJsonObject(); if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { if(json.get("access_token").getAsString() != null){ // 获取结果 result = json.get("access_token").getAsString(); } } } catch (Exception e) { e.printStackTrace(); } finally { // 关闭连接 ,释放资源 client.getConnectionManager().shutdown(); return result; } } }
需要注意的是,get和post请求方式不一样的地方是post需要创建简单名称值对节点类型的集合,然后将集合设置成post提交的参数,用"UTF-8"方式提交。
对于返回的结果,可以预先用谷歌的postman插件进行测试,针对不同的结果用JsonParser进行解析成jsonobject或者jsonarray。
当然,实际情况中POST请求的还有可能是Json格式的参数,此处需要JSONObject进行封装,同时针对返回结果,也可以封装成一个javaBean,代码如下:public class CustomerRegisterUtils {
// 客户注册
public static ResultCustomerRegister registerCustomer(String access_token, String mobile, String wx_open_id, String wx_union_id){
// 设置json格式的参数
JSONObject params = new JSONObject();
params.put("mobile", mobile);
params.put("wx_open_id", wx_open_id);
params.put("wx_union_id", wx_union_id);
// 获取接口
Properties pro = PropertyUtil.getPropertys("access_token.properties");
String apiurl = (String) pro.get("CUSTOMER_REGISTER_URL");
// 拼接url
String url = String.format("%s?access_token=%s", apiurl, access_token);
// 创建httpclient对象
HttpClient client = new DefaultHttpClient();
// post请求方式
HttpPost post = new HttpPost(url);
// 返回结果
ResultCustomerRegister registerResult = null;
// 设置参数
try {
StringEntity stringEntity = new StringEntity(params.toString(), "UTF-8");
//发送json数据需要设置contentType
stringEntity.setContentType("application/json");
post.setEntity(stringEntity);
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
try
{
HttpResponse res = client.execute(post);
// 响应内容
HttpEntity entity = res.getEntity();
String responseContent = EntityUtils.toString(entity, "UTF-8");
// 将结果转化为bean对象
JSONObject object = JSONObject.fromObject(responseContent);
registerResult = (ResultCustomerRegister) JSONObject.toBean(object,ResultCustomerRegister.class);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
// 关闭连接 ,释放资源
client.getConnectionManager().shutdown();
return registerResult;
}
}
}
相关文章推荐
- restful接口客户端和服务端开发,HttpURLConnection,HttpClient,post ,get方式调用
- Go语言服务器开发实现最简单HTTP的GET与POST接口
- 门面模式的典型应用 Socket 和 Http(post,get)、TCP/IP 协议的关系总结
- 在线HTTP接口测试 - HTTP GET/POST模拟请求测试工具
- 如何调用http接口通过get()/post()方法传参
- 使用WinHttp接口实现HTTP协议Get、Post和文件上传功能
- 使用HttpURLConnection开发自动发送Get、Post请求并获取响应
- HttpClient应用案例post&get方法
- http客户端开发get、Post两种方式
- 如何开发一接口 要求是外界会通过POST方法向HTTP发送一个xml文件
- .NET获取聚合数据接口数据(Http协议POST和GET请求)
- LR接口测试---基于http协议之get/post
- HTTP 中 GET 与 POST 应用场景区别
- 后端开发--Http协议(3):Get与Post方法的比较
- python httplib2应用get post
- pbfunc外部函数扩展应用-在Powerbuilder中进行Http的GET、POST操作
- Android HTTP实例 使用GET方法和POST方法发送请求(通过Apache接口实现)
- HTTP请求接口方法(POST/GET)
- JAVA发送HTTP请求(post、get),读取HTTP响应内容,实例及应用
- Android开发 HTTP 发送 Post 与 Get 请求