aysunzheng
2017-03-06 07:42
采纳率: 100%
浏览 2.5k
已采纳

关于c#使用WebClient调用openapi接口

使用c#调用openapi接口。如下图
图片说明
java代码为:

public static PageResponse<UIMUser> userfind() {
        List<CommonCondition> conditions = new ArrayList<CommonCondition>();
        CommonCondition c = new CommonCondition();
        c.setName("userName");
        c.setDataType(DataType.String);
        c.setCriteriaType(CriteriaType.StartWith);
        c.setValue("User1");
        conditions.add(c);
        PostMethod method = new PostMethod(endPoint + "/admin/macula-uim/user/find");
        try {
            method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            // 标识是OpenAPI请求
            method.addRequestHeader(OpenApiUtils.AJAX_REQUEST_HEADER, OpenApiUtils.API_REQUEST_VALUE);
            // 添加POST BODY
            method.addParameter("page", "0");
            method.addParameter("rows", "20");
            method.addParameters(OpenApiUtils.getPostParams("conditions", conditions));
            // 设置请求参数
            method.setQueryString(OpenApiUtils.getOpenApiParams(appKey, appSecret, null, null, null, null,
                    "zh_CN", method.getParameters()));

            int status = client.executeMethod(method);
            String content = method.getResponseBodyAsString();

            if (status == HttpServletResponse.SC_OK || status == HttpServletResponse.SC_INTERNAL_SERVER_ERROR) {
                // 反序列化结果
                ObjectMapperImpl mapper = new ObjectMapperImpl();
                return mapper.readValue(content, new TypeReference<PageResponse<UIMUser>>() {
                });
            } else {
                throw new Exception("错误的请求");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            method.releaseConnection();
        }
        return null;
    }
public static NameValuePair[] getPostParams(String objectName, Object obj) {
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        if (obj != null) {
            if (obj instanceof Map) {
                // 处理Map
                Map<?, ?> map = (Map<?, ?>) obj;
                for (Map.Entry<?, ?> entry : map.entrySet()) {
                    Object key = entry.getKey();
                    Object value = entry.getValue();
                    if (null != value) {
                        pairs.addAll(Arrays.asList(getPostParams(objectName + "['" + key + "']", value)));
                    }
                }
            } else if (obj instanceof Collection) {
                // 处理Collection
                Collection<?> col = (Collection<?>) obj;
                Iterator<?> it = col.iterator();
                int index = 0;
                while (it.hasNext()) {
                    Object value = it.next();
                    if (null != value) {
                        pairs.addAll(Arrays.asList(getPostParams(objectName + "[" + index++ + "]", value)));
                    }
                }
            } else if (!BeanUtils.isSimpleProperty(obj.getClass()) && !(obj instanceof Enum) && !Date.class.isAssignableFrom(obj.getClass())) {
                // 处理Bean
                BeanWrapperImpl bean = new BeanWrapperImpl(obj);
                PropertyDescriptor[] ps = bean.getPropertyDescriptors();
                for (PropertyDescriptor p : ps) {
                    if (!p.getName().equals("class")) {
                        Object value = bean.getPropertyValue(p.getName());
                        if (null != value) {
                            pairs.addAll(Arrays.asList(getPostParams(objectName + "." + p.getName(), value)));
                        }
                    }
                }
            } else {
                String str = obj.toString();
                // 处理简单属性
                // 日期格式使用ISO8601
                if (obj instanceof Date) {
                    str = DateFormatUtils.formatISO8601((Date) obj);
                }
                pairs.add(new NameValuePair(objectName, str));
            }
        }
        return pairs.toArray(new NameValuePair[pairs.size()]);
    }
现在不清楚使用c#怎么传递第一个参数。
我自己写的代码:
      using (WebClient client = new WebClient())
            {
                //SyncOrgDAL dal = new SyncOrgDAL();
              //  List<CommonCondition> conditions = new List<CommonCondition>();
                //CommonCondition c = new CommonCondition();
                //c.setName("userType");
                //c.setDataType(DataType.String);
                //c.setCriteriaType(CriteriaType.Equals);
                //c.setValue("User1");
                //conditions.Add(c);
                NameValueCollection postParams = new NameValueCollection { { "conditions", "[\"conditions\":{\"UserName\":\"Exp\",\"userType\":\"Exp\"}]" }, { "page", page.ToString() }, { "rows", pagesize.ToString() } };
                //NameValueCollection postParams = new NameValueCollection { { "fromId", "302264246" }, { "toId", "99999999999" } };

                string passString = Parameters.GetOpenApiParams(account, passWord, null, null, null, null, "zh_CN", postParams);
                //passString += "&userType=EMP";
                url += passString;
                client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                client.Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
                client.Headers.Add("X-Requested-With", "OpenAPIRequest");
                client.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0");
                try
                {
                    byte[] rDownData = client.UploadValues(url, "POST", postParams);
                    var downString = Encoding.UTF8.GetString(rDownData) ?? "";

                    return downString;
                }
                catch (Exception ex)
                {
                    return ex.ToString();
                }
                finally
                {
                    client.Dispose();
                    GC.Collect();
                }

NameValueCollection postParams = new NameValueCollection { { "conditions", "[\"conditions\":{\"UserName\":\"Exp\",\"userType\":\"Exp\"}]" }, { "page", page.ToString() }, { "rows", pagesize.ToString() } }; 第一个参数什么格式。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • blownewbee 2017-03-06 07:43
    已采纳

    C#没有httpclient,对应的等价类叫做httpwebrequest。你写的对不对,可以用fiddler抓包比下。一目了然

    点赞 评论

相关推荐 更多相似问题