zoukankan      html  css  js  c++  java
  • WebApi HttpUtils

    public class HttpUtils {
        private static final String TAG = "uploadFile";
        private static final int TIME_OUT = 100 * 1000;//超时时间
    
        /**
         * 通过GET方式发送请求
         *
         * @param url    URL地址
         * @param params 参数
         */
        public static String httpGet(String url, String params) {
            //返回信息
            String response = null;
            try {
                //拼接请求地址
                StringBuilder urlBuilder = new StringBuilder();
                urlBuilder.append(url);
                if (null != params && !params.equals("")) urlBuilder.append("?" + params);
                // 构造HttpClient的实例
                HttpClient httpClient = new DefaultHttpClient();
                // 创建GET方法的实例
                HttpGet getMethod = new HttpGet(urlBuilder.toString());
                //设置请求APIToken和请求方式
                getMethod.addHeader("Accept-Language", WebApiUrl.Accept_Language);
                getMethod.addHeader("Authorization", "Basic " + WebApiUrl.Authorization);
                getMethod.addHeader("Content-Type", WebApiUrl.Content_Type);
    
                //获取HTTP请求响应结果
                HttpResponse httpResponse = httpClient.execute(getMethod);
                int statusCode = httpResponse.getStatusLine().getStatusCode();
                if (statusCode == HttpStatus.SC_OK) //SC_OK = 200
                {
                    // 获得返回结果
                    response = EntityUtils.toString(httpResponse.getEntity());
                }
            } catch (Exception ex) {
                Log.i(TAG, String.format("HttpGet请求发生异常:{0}", ex.toString()));
            }
            return response;
        }
    
        /**
         * 通过POST方式发送请求
         *
         * @param url    URL地址
         * @param params 参数
         */
        public static String httpPost(String url, String params) {
            String result = null;
            try {
                StringEntity entity = new StringEntity(params, "utf-8");
                entity.setContentType("application/json");
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(entity);
                httpPost.addHeader("Authorization", "Basic " + WebApiUrl.Authorization);
                // 构造HttpClient的实例
                HttpClient client = new DefaultHttpClient();
                HttpResponse response = client.execute(httpPost);
                HttpEntity responseEntity = response.getEntity();
                result = EntityUtils.toString(responseEntity, "UTF-8");
            } catch (Exception ex) {
                Log.i(TAG, String.format("HttpPost请求发生异常:{0}", ex.toString()));
            }
            return result;
        }
    }

    Post请求案例
    实例一:接口入参为对象

    public ManagementBagRsult ManagementDetainedBags(DetentionBagParam param) {       
    Gson os=new Gson(); String paramStr=os.toJson(param); try { String result = HttpUtils.httpPost(WebApiUrl.ManagementDetainedBags_Url,paramStr); ManagementBagRsult info = os.fromJson(result, ManagementBagRsult.class); return info; } catch (Exception ex) { Log.i("TAG", String.format("ScanBagInfoContractImpl/ManagementDetainedBags:{0}", ex.toString())); return null; } }

    实例二:接口入参为String单个属性

    public class LoginContractImpl implements ILoginContract {
        private static final Logger logger = LoggerFactory.getLogger();
        @Override
        public ApLoginResult  doLogin(DetentionBagParam param) {
            try {
                //传入参数,获得结果集
                String result = HttpUtils.httpPost(WebApiUrl.Login_Url+"?OrganizationCode="+param.OrganizationCode+"&UserWorkNumber="+param.UserWorkNumber+"&UserPassWord="+param.UserPassWord, "");
                //序列化一个泛型对象
                Gson gs = new Gson();
                ApLoginResult info = gs.fromJson(result, ApLoginResult.class);
                return info;
            } catch (Exception ex) {
                logger.info(String.format("LoginContractCompl发生异常:{0}", ex.toString()));
                return null;
            }
        }
    }

    实例三:GET请求

    public Boolean SetLocactionIsFull(String locaton_code) {
            String params="location_code="+locaton_code;
            try {
                String result=HttpUtils.httpGet(WebApiUrl.SetLocactionIsFull_Url, params);
                //获取对应的值
                if (result == null) return false;
                //反序列化一个泛型对象
                Gson gs = new Gson();
                Type jsonType = new TypeToken<RequestModel.Request<Boolean>>() {}.getType();
                RequestModel.Request<Boolean> res= gs.fromJson(result, jsonType);
                if(res!=null && res.ResultCode.equals("0000") && res.ResultDesc.equals("接口调用成功")){
                    return res.Item;
                }
            } catch (Exception ex) {
                logger.info(String.format("{0}/{1}发生异常:{2}", "QuickShelfContractImpl", "InStoresOperating", ex.toString()));
            }
            return false;
    }
  • 相关阅读:
    回顾:异常处理,值传递和引用传递
    回顾:静态变量和实例变量、构造器
    多态、抽象类与接口
    回顾:面向对象、基本类型
    总结一下《深入理解Java虚拟机》
    百度实习生面试题
    面试题
    阿里面试
    Shell
    Collector详解
  • 原文地址:https://www.cnblogs.com/xmyjcs/p/10423056.html
Copyright © 2011-2022 走看看