HttpClient从C在Java中复制#

HttpClient从C在Java中复制#,java,c#,android,json,xamarin,Java,C#,Android,Json,Xamarin,我有一个在Xamarin(.NET)中构建的Android项目,我希望将其转换为本机Java。在Xamarin应用程序中,我构建了一个API类,用于使用泛型访问HTTP数据,如下所示: public class InventoryAPI { HttpClientHandler handler; Uri baseAddress; HttpClient client; public InventoryAPI() { // .. Init code here } public async Ta

我有一个在Xamarin(.NET)中构建的Android项目,我希望将其转换为本机Java。在Xamarin应用程序中,我构建了一个API类,用于使用泛型访问HTTP数据,如下所示:

public class InventoryAPI {
HttpClientHandler handler;
Uri baseAddress;
HttpClient client;

public InventoryAPI() {
  // .. Init code here
}

public async Task<Response> EnrolMultipleItemsAsync(EnrolItemModel[] _items) {
    try {
        var result = await PostAsync<Response>("api/inventory/enrolmultipleitems", _items);
        Console.WriteLine(result.Message);
        return result;
    }
    catch (Exception ex) {
        App.Current.Logger.LogInfo("Exception at InventoryAPI - Error: EnrolItemAsync:");
        App.Current.Logger.LogError(ex.Message);
        throw ex;
    }
}
public Response EnrolMultipleItems(EnrolItemModel[] _items) {
    try {
        var result = Post<Response>("api/inventory/enrolmultipleitems", _items);
        return result;
    }
    catch (Exception ex) {
        App.Current.Logger.LogInfo("Exception at InventoryAPI - Error: EnrolItem:");
        App.Current.Logger.LogError(ex.Message);
        throw ex;
    }
}

private async Task<T> PostAsync<T>(string apiLocation, object postData) {
    var response = await client.PostAsync(apiLocation, postData.ToHttpContentString());
    T result = default(T);
    if (response.StatusCode == HttpStatusCode.OK) {
        var json = await (response.Content.ReadAsStringAsync());
        result = DeserializeJson<T>(json);
    }
    return result;
}

private T Post<T>(string apiLocation, object postData) {
    var response = client.PostAsync(apiLocation, postData.ToHttpContentString()).Result;
    T result = default(T);
    if (response.StatusCode == HttpStatusCode.OK) {
        var json = response.Content.ReadAsStringAsync().Result;
        result = DeserializeJson<T>(json);
    }
    return result;
}
public T DeserializeJson<T>(string json) {
    var parsed = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json);
    return parsed;
}
}
公共类InventoryAPI{
HttpClientHandler处理器;
Uri基地址;
HttpClient;
公共资源清册API(){
//…这里是初始化代码
}
公共异步任务EnrolMultipleItemsAsync(EnrolItemModel[]\u项){
试一试{
var结果=等待邮资同步(“api/库存/注册多个项目”);
Console.WriteLine(result.Message);
返回结果;
}
捕获(例外情况除外){
App.Current.Logger.LogInfo(“InventoryAPI异常-错误:EnrolItemAsync:”);
App.Current.Logger.LogError(例如消息);
掷骰子;
}
}
公众响应注册多个项目(EnrolItemModel[]\u项目){
试一试{
var结果=Post(“api/存货/注册倍数”、\u项目);
返回结果;
}
捕获(例外情况除外){
App.Current.Logger.LogInfo(“InventoryAPI异常-错误:EnrolItem:”);
App.Current.Logger.LogError(例如消息);
掷骰子;
}
}
专用异步任务PostAsync(字符串apiLocation,对象postData){
var response=wait client.PostAsync(apiLocation,postData.ToHttpContentString());
T结果=默认值(T);
if(response.StatusCode==HttpStatusCode.OK){
var json=await(response.Content.ReadAsStringAsync());
结果=反序列化json(json);
}
返回结果;
}
私有T Post(字符串位置、对象postData){
var response=client.PostAsync(apiLocation,postData.ToHttpContentString()).Result;
T结果=默认值(T);
if(response.StatusCode==HttpStatusCode.OK){
var json=response.Content.ReadAsStringAsync().Result;
结果=反序列化json(json);
}
返回结果;
}
公共T反序列化json(字符串json){
var parsed=Newtonsoft.Json.JsonConvert.DeserializeObject(Json);
返回解析;
}
}
我喜欢这种风格的API,它在Xamarin应用程序中运行得很好,所以现在我希望将其移植到Java——这就是我的困境所在

以下是我目前掌握的情况:

public class APIDownloader extends AsyncTask<String, Void, String> {

@Override
protected String doInBackground(String... ts) {
    String url = ts[0].toString();
    return Get(url);
}

private String Get(String url) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(url);

    HttpEntity entity = null;
    String result = "";

    try {
        //Execute and get the response.
        HttpResponse response = httpclient.execute(httpget);
        entity = response.getEntity();

        if (entity != null) {
            result = EntityUtils.toString(entity);
            //final JSONArray jObject = new JSONArray(EntityUtils.toString(entity));
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Catch no internet connectivity exception
        e.printStackTrace();
    }
    return result;
  }
}
公共类APIDownloader扩展异步任务{
@凌驾
受保护的字符串背景(字符串…ts){
字符串url=ts[0]。toString();
返回Get(url);
}
私有字符串获取(字符串url){
HttpClient HttpClient=新的DefaultHttpClient();
HttpGet HttpGet=新的HttpGet(url);
HttpEntity=null;
字符串结果=”;
试一试{
//执行并获得响应。
HttpResponse response=httpclient.execute(httpget);
entity=response.getEntity();
如果(实体!=null){
结果=EntityUtils.toString(实体);
//final JSONArray jObject=新的JSONArray(EntityUtils.toString(entity));
}
}捕获(不支持的编码异常e){
e、 printStackTrace();
}捕获(客户端协议例外e){
e、 printStackTrace();
}捕获(IOE异常){
//TODO未捕获任何internet连接异常
e、 printStackTrace();
}
返回结果;
}
}
然后是一个单独的API类:

public class InventoryAPI {

public List<LocationModel> GetAllLocations() throws IOException {
    String url = "https://domain.com/api/inventory/getall";
    String response = null;// Get(url);

    try {
        response = new APIDownloader().execute(url).get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }

    Gson gson = new Gson();
    LocationModel[] mcArray = gson.fromJson(response, LocationModel[].class);
    return Arrays.asList(mcArray);
  }
}
公共类InventoryAPI{
公共列表GetAllLocations()引发IOException{
字符串url=”https://domain.com/api/inventory/getall";
字符串响应=null;//获取(url);
试一试{
response=new APIDownloader().execute(url.get();
}捕捉(中断异常e){
e、 printStackTrace();
}捕获(执行例外){
e、 printStackTrace();
}
Gson Gson=新的Gson();
LocationModel[]mcArray=gson.fromJson(响应,LocationModel[].class);
返回array.asList(mcArray);
}
}
虽然上面的Java代码工作得很好(我只实现了GET,到目前为止),但它似乎很快就会失控,特别是在我将C#库中的POST方法移植到Java包之后


在Java中复制我上面提到的Xamarin API类的最佳方法是什么?

如果您打算使用原生Java,请帮自己一个忙并使用它。这将在API层中为您节省大量代码。普通的JavaHTTP东西很难看,改型使它更容易


当你觉得舒服的时候,看看能对你的一些异步代码有什么帮助。

“。它看起来很快就会失控……”欢迎使用Java.)但严肃地说,有比
AsyncTask
s更好的方法来设计API,但是您的问题太模糊,无法简洁地回答,并且过于依赖于意见(即使用此设计模式或此库),imo。