Итак, я пытаюсь сделать пост из Java. К моему .net core webapi. Пост формы работал очень хорошо, пока я не добавил требование отправки массива внутреннего объекта. Я хочу верить, что когда я делаю свое сообщение, мой .net не понимает полезную нагрузку, которую он получает. Поэтому приведенный ниже код Java отправляет значения в ядро .net. После того, как модели, которые должны собирать (связывать), запрос из кода Java также вставляется
// Этот метод будет отправлять значения в .net
public <T> T Handlepost(File inFile,Productmodel model,final Class<T> objectClass) {
FileInputStream fis = null;
try {
StringBody name = new StringBody(model.getName());
StringBody barcode = new StringBody(model.getBarcode());
StringBody quantity = new StringBody(model.getStockQuantity()+"");
StringBody unitcost = new StringBody(model.getUnitCost()+"");
StringBody discountamt = new StringBody(model.getDiscountamt()+"");
StringBody describe = new StringBody(model.getDescription());
StringBody companyid = new StringBody(model.getCompanyID()+"");
StringBody unitid = new StringBody(model.getUnit().getID());
StringBody inventorycatid = new StringBody(model.getProductposcategory().getID());
String hascolors = "";
if(model.getHascolortypes()){
hascolors = "yes";
}
else
hascolors = "no";
StringBody hascolortypes = new StringBody(hascolors);
if(inFile != null){
fis = new FileInputStream(inFile);
}
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
String Posturl = urlobject.Createproducturl();
// server back-end URL
HttpPost httppost = new HttpPost(Posturl); //"http://localhost:56175/api/product/create"
MultipartEntity entity = new MultipartEntity();
// set the file input stream and file name as arguments
if(inFile != null)
entity.addPart("Image", new InputStreamBody(fis, inFile.getName()));
entity.addPart("Name", name);
entity.addPart("Barcode",barcode);
entity.addPart("StockQuantity", quantity);
entity.addPart("UnitCost", unitcost);
entity.addPart("Discountamt", discountamt);
entity.addPart("Description", describe);
entity.addPart("CompanyID", companyid);
entity.addPart("Unit.ID",unitid);
entity.addPart("Hascolortypes", hascolortypes);
entity.addPart("InventorycategoryID",inventorycatid);
// Gson gson = new Gson();
/* String json = new JSONArray(model.getCostpersizes()).toString(); //gson.toJson(model.getCostpersizes());
StringBody productprices = new StringBody(json);
entity.addPart("Costpersizes", productprices);*/
// Этомассив внутреннего объекта. Я использую его для сбора нескольких вариантов от моих пользователей. Поэтому я должен отправить массив объекта в моей полезной нагрузке на мой контроллер .net.
//Adding array to the Product post object
if(model.getCostpersizes() != null ){
for(int k=0; k<model.getCostpersizes().size(); k++){
Productpricemodel pricemodel = model.getCostpersizes().get(k);
entity.addPart("Costpersizes[].SN", new StringBody(pricemodel.getSN()));
entity.addPart("Costpersizes[].ProductID", new StringBody(pricemodel.getProductID()));
entity.addPart("Costpersizes[].AvailableQuantity", new StringBody(pricemodel.getAvailableQuantity()+""));
entity.addPart("Costpersizes[].Barcode", new StringBody(pricemodel.getBarcode()));
entity.addPart("Costpersizes[].Cost", new StringBody(pricemodel.getCost()+""));
entity.addPart("Costpersizes[].Size.ID", new StringBody(pricemodel.getSize().getID()));
entity.addPart("Costpersizes[].Response", new StringBody(pricemodel.getResponse()));
}
}
System.out.println("This is the string reprensentaion of the object that was sent to the server");
System.out.println(entity.toString());
httppost.setEntity(entity);
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Accept-Encoding", "gzip");
if(Main.LicenseToken != null){
httppost.setHeader("Authorization",Main.LicenseToken); //I just added this here
}
// execute the request
HttpResponse httpResponse = httpclient.execute(httppost);
int statusCode = httpResponse.getStatusLine().getStatusCode();
HttpEntity responseEntity = httpResponse.getEntity();
/*
String responseString = EntityUtils.toString(responseEntity, "UTF-8");
System.out.println("[" + statusCode + "] " + responseString);*/
if (responseEntity != null) {
InputStream inputStream = responseEntity.getContent();
Header contentEncoding = httpResponse.getFirstHeader("Content-Encoding");
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
inputStream = new GZIPInputStream(inputStream);
}
String resultString = convertStreamToString(inputStream);
System.out.println("output "+resultString);
inputStream.close();
return new GsonBuilder().create().fromJson(resultString, objectClass);
}
} catch (ClientProtocolException e) {
System.err.println("Unable to make connection");
e.printStackTrace();
} catch (IOException e) {
System.err.println("Unable to read file");
e.printStackTrace();
}
finally {
try {
if (fis != null) fis.close();
} catch (IOException e) {}
}
return null;
}
private String convertStreamToString(InputStream inputStream) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
try {
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
} catch (IOException e) {
System.out.println("first "+e.toString());
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} finally {
try {
inputStream.close();
} catch (IOException e) {
System.out.println("second "+e.toString());
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
return stringBuilder.toString();
}
}
Проблема с кодом выше - это попытка отправить массиввнутренний объектЭта часть приведенного выше кода вызывает у меня проблемы:
//Adding array to the Product post object
if(model.getCostpersizes() != null ){
for(int k=0; k<model.getCostpersizes().size(); k++){
Productpricemodel pricemodel = model.getCostpersizes().get(k);
entity.addPart("Costpersizes[].SN", new StringBody(pricemodel.getSN()));
entity.addPart("Costpersizes[].ProductID", new StringBody(pricemodel.getProductID()));
entity.addPart("Costpersizes[].AvailableQuantity", new StringBody(pricemodel.getAvailableQuantity()+""));
entity.addPart("Costpersizes[].Barcode", new StringBody(pricemodel.getBarcode()));
entity.addPart("Costpersizes[].Cost", new StringBody(pricemodel.getCost()+""));
entity.addPart("Costpersizes[].Size.ID", new StringBody(pricemodel.getSize().getID()));
entity.addPart("Costpersizes[].Response", new StringBody(pricemodel.getResponse()));
}
}
Вот мой объект .net, который я использую для сбора значений, отправленных в форму
public class Product
{
public IFormFile Image { get; set; }
public OptionSelect Unit { get; set; }
public string Name { get; set; }
public string Barcode { get; set; } //This is code is used to prove originality of the product
public int StockQuantity { get; set; }
public double UnitCost { get; set; }
public int Discountamt { get; set; }
public string Description { get; set; }
public int CompanyID { get; set; }
// public List<OptionSelect> Producttags { get; set; }
public string Hascolortypes { get; set; }
public List<Productpricemodel> Costpersizes { get; set; }
public string InventorycategoryID { get; set; }
}
public class Productpricemodel
{
[JsonProperty("sn")]
public string SN { get; set; }
[JsonProperty("cost")]
public float Cost { get; set; }
[JsonProperty("productID")]
public string ProductID { get; set; }
[JsonProperty("size")]
public OptionSelect Size { get; set; }
[JsonProperty("availablequantity")]
public double AvailableQuantity { get; set; }
[JsonProperty("barcode")]
public string Barcode { get; set; }
[JsonProperty("response")]
public string Response { get; set; }
}
Поэтому, пожалуйста,Как мне опубликовать в
public List<Productpricemodel> Costpersizes { get; set; }
С Java. Проводка внутреннего объекта Array. потел уже несколько дней.