java 异步调用webapi_使用httpclient异步调用WebAPI接口

这个博客展示了如何在Java中使用HttpClient库进行异步调用WebAPI接口。通过创建一个名为GarmentStyleHelper的类,实现了异步搜索GarmentStyle的功能。博客详细步骤包括设置请求参数、处理身份验证、发送POST请求以及处理返回结果。
摘要由CSDN通过智能技术生成

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Net.Http;usingSystem.Threading.Tasks;usingSystem.Web;usingSystem.Text;usingNewtonsoft.Json;usingSystem.Net;namespaceesquel_LPD_Bot.LPDService

{public classGarmentStyleHelper

{public async Task GarmentStyleSearch(stringpi_GarmentStyleNo)

{string l_returnValue = string.Empty;string l_APIUrl = Common.ConfigHelper.GetConfigValue("LPD-GarmentStyleSearchAPIUrl");

Common.LPDAuthHelper LPDAuthClass= newCommon.LPDAuthHelper();try{if(string.IsNullOrEmpty( LPDAuthClass.UserName)|| string.IsNullOrEmpty(LPDAuthClass.UserName))

{throw new Exception("LPD Project Auth User Name Or Password Is Empty .");

}if (!string.IsNullOrEmpty(l_APIUrl) && !string.IsNullOrEmpty(pi_GarmentStyleNo))

{var request = newModel.SelectionFilter()

{

FilterType=Model.SelectionFilter.FilterTypeLeaf,

Filters= newModel.SelectionFilter[] { },

AttributeName= "item_number",

FilterValue=pi_GarmentStyleNo

};//--------------------------------------------------------------------------------------------

var handler = newHttpClientHandler()

{

AutomaticDecompression=System.Net.DecompressionMethods.GZip

};//handler.UseDefaultCredentials = true;//use default network利用的用户本机的网络,但因为需要布署到服务器,所以使用以下这一句

handler.Credentials=newNetworkCredential(LPDAuthClass.UserName, LPDAuthClass.PassWord);//设定权限,这一句比较痛苦,找了很久using (var client = newHttpClient(handler))

{

client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));var response = await client.PostAsync(l_APIUrl, new StringContent(JsonConvert.SerializeObject(request).ToString(), Encoding.UTF8, "application/json"));

response.EnsureSuccessStatusCode();string l_getreturn = awaitresponse.Content.ReadAsStringAsync();

l_returnValue=l_getreturn;

}

}

}catch(Exception ex)

{

}returnl_returnValue;

}

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值