关于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个回答

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

aysunzheng
aysunzheng 回复aysunzheng: 我现在的问题是调用可以成功,但是参数的格式不对啊。不知道该怎么传递
接近 3 年之前 回复
aysunzheng
aysunzheng 回复caozhy: 没用过fiddler啊,可以加您qq吗?
接近 3 年之前 回复
caozhy
每个人都有一个梦才不会孤单的说话就有天堂 回复aysunzheng: fiddler抓包比较,哪里不同改哪里,直到相同
接近 3 年之前 回复
aysunzheng
aysunzheng 回复caozhy: 是啊,就是不知道怎么能对上。求赐教!
接近 3 年之前 回复
caozhy
每个人都有一个梦才不会孤单的说话就有天堂 回复aysunzheng: 不用管java代码,只要http报文对上就可以。可能condition是postdata吧
接近 3 年之前 回复
aysunzheng
aysunzheng 接口方还有其他接口,只要是没有List<CommonCondition> conditions这种类型的参数,int,string,long都没问题
接近 3 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问