接口开发中的httpget和httppost的应用

        参加新工作一周有余,领导安排任务写几个接口开发。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请求参数:

参数名

是否必选

类型

说明

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

凭证有效期,单位:秒

其实也不难,之前没写过,问问同事,终于懂了需求,就是写一个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类进行处理,具体代码如下:

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;
     }
 }
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值