使用HttpClient 后台调用接口_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > 使用HttpClient 后台调用接口

使用HttpClient 后台调用接口

 2017/11/30 13:05:12  行_天下  程序员俱乐部  我要评论(0)
  • 摘要://接口与对象的条件绑定并返回json数据publicstaticStringexecuteHttpRequestByGetType(Stringurl,Objectobj){HttpClientclient=newHttpClient();StringBuffersb=newStringBuffer(url);Map<String,String>keyValueMap=objectToMap(obj);PostMethodpostMethod=null;try
  • 标签:使用 client 接口 HTTP
class="java" name="code">//接口与对象的条件绑定并返回json数据
public static String executeHttpRequestByGetType(String url,Object obj ) {  
	HttpClient client = new HttpClient();  
	StringBuffer sb = new StringBuffer(url);  
	Map<String, String> keyValueMap=objectToMap(obj);
	PostMethod postMethod = null;  
	try {  
	    //设置请求参数  
	    if (keyValueMap != null) {  
	        Iterator it = keyValueMap.entrySet().iterator();  
	        if (keyValueMap.size() > 0) {  
	            sb.append("?");  
	             while (it.hasNext()) {  
	                  Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next();  
	                  sb.append(entry.getKey() + "=" + entry.getValue() + "&");  
	              }  
	             sb.deleteCharAt(sb.length()-1);  
	         }  
	     }  
	     postMethod = new PostMethod(sb.toString());  
	     //log.debug("query uri ===============" + postMethod.getURI()); 
	     // 设置成了默认的恢复策略,在发生异常时候将自动重试3次,
	     postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());  
	     //设置参数编码为gbk
	     postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");  
	     //设置超时时间  
	     postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 200000);
	     //HttpClient第一步中创建好的实例的 executeMethod 方法来执行第二步中创建好的 method 实例
	     int statusCode = client.executeMethod(postMethod);  
	     if (statusCode != HttpStatus.SC_OK) {  
	         //log.info("request '" + url + "' failed,the status is not 200,status:" + statusCode);  
	         return "";  
	     }  
	     String responseBody = postMethod.getResponseBodyAsString();  
	     return responseBody;  
	     } catch (Exception e) {  
	            //log.error("发生异常!请检查网络和参数", e);  
	      } finally {  
	            if(postMethod!=null){  
	               postMethod.releaseConnection();  
	            }  
	        }  
	      return null;  
       }
@Test
public void test(){
	TestBean be=new TestBean();
	InterfaceData da=new InterfaceData();
	String url= "http://59.111.44.97:9096/webapi/TakeAll";//接口地址
	Map<String, String> msp=new HashMap<String, String>();
	String s=da.executeHttpRequestByGetType(url,be);
	//JSONUtil.deserialize(s);
	System.out.println(s);
 }
	 
//object转化为Map
public static Map<String,String> objectToMap(Object obj){
        Map<String,String> map=null;
        if(obj==null){
	   return map;
	}else{
	   try {
		map= new HashMap<String,String>();
		BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
		PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
		for (PropertyDescriptor property : propertyDescriptors) {    
		      String key = property.getName();    
		      if (key.compareToIgnoreCase("class") == 0) {   
		          continue;  
		      }  
		      Method getter = property.getReadMethod();  
		      Object value = getter!=null ? getter.invoke(obj) : null;
		      if(value!=null){
		       	map.put(key, value.toString());  
		       }
		   }    
		  return map;  
		  } catch (IntrospectionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		  }catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		  } catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		  } catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		  } 
		return null;
	     }
     }

?

发表评论
用户名: 匿名