HttpClient Replicate in Java from C#

本文关键字:from Java in Replicate HttpClient | 更新日期: 2023-09-27 18:31:04

我有一个用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;
}
}

我喜欢这种风格的 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;
  }
}

然后是一个单独的 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);
  }
}

虽然上面的 Java 代码确实工作得很好(到目前为止我只实现了 GET),但它似乎很快就会失控,尤其是在我将 C# 库中的 POST 方法移植到 Java 包之后。

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

HttpClient Replicate in Java from C#

如果你打算使用原生Java,那就帮自己一个忙,使用Retrofit。这将在 API 层中为您节省大量代码。常规的Java Http东西很丑陋,Retrofit使它变得容易得多。

当你感到舒服时,看看RxAndroid(RxJava)来真正帮助你的一些异步代码。