Web API 2无法读取通过Retrofit 2发送的byte []

时间:2016-09-07 13:39:02

标签: android upload asp.net-web-api2 retrofit2

我正在尝试使用Retrofit 2&amp ;;将客户端sq-lite数据库中的对象上传到MSSQL。 Web API 2.

如果我为访问分配nullnew byte[1000],该应用可以正常运行。图像,但无论何时从sq-lite数据库检索其指定值,我都会得到错误响应代码400

{
  "Message": "The request is invalid.",
  "ModelState": {
    "visit.Image[0]": [
      "An error has occurred."
    ],
    "visit.Image[1]": [
      "An error has occurred."
    ]
  }
}

这是我在android中的模型:

public class Visit {
    public int VisitId;
    public String DealerMId;
    public byte[] Image; // read image from database (blob data type)
}

这是我从数据库中检索值并制作访问对象

的代码
public Visit getVisitByVisitId(long visitId) {
        SQLiteDatabase db = this.getReadableDatabase();

        String selectQuery = "SELECT  * FROM " + TABLE_VISIT + " WHERE "
                + KEY_ID + " = " + visitId;
        Cursor c = db.rawQuery(selectQuery, null);

        if (c != null)
            c.moveToFirst();

        Visit visit = new Visit();

        visit.VisitId = c.getInt(c.getColumnIndex(KEY_ID));
        visit.DealerMId = c.getString(c.getColumnIndex(KEY_DEALER_MID));
        visit.Image= c.getBlob(c.getColumnIndex(KEY_PICTURE));

        return visit ;
    }

这是改装服务的使用界面:

@POST("visits/PostVisit")
public Call<Integer> postVisit(@Body Visit visit);

这是活动代码:

Visit vistit = db.getVisitById(1) ;

// Note that : every thing working fine 
// if visit.Image = null or visit.Image = new byte[1000] or visit.Image = new byte[]{1,4,3 ..}
// but I am receiving error 400 when visit.Image contains value from database

Call<Integer> call = RetrofitService.postVisit(visit);    

call.enqueue(new Callback<Integer>() {
          @Override
          public void onResponse(Call<Integer> call, Response<Integer>response){
                    //....
            }
          @Override
          public void onFailure(Call<Integer> call, Throwable t) {
                    //....
            }
});

此Web API 2代码

[HttpPost]
public IHttpActionResult PostVisit(Visit visit)
{

    if (!ModelState.IsValid)
    {
         return BadRequest(ModelState);
    }

    db.Visits.Add(visit);

    try
    {
        db.SaveChanges();
    }
    catch (DbUpdateException)
    {
        if (VisitExists(visit.VisitId))
        {
            return Ok(-1);
        }
        else
        {
            throw;
        }
    }
    return Ok(visit.VisitId);
}

android studio下面的截图显示了Visit.Image的检索内容,我确信它自己的内容没有问题,因为我可以在ImageView的Android应用程序中阅读它。

This is a screen shot from android studio taken when I was debugging the code, it shows the Visit.Image value which is retrieved from the database

2 个答案:

答案 0 :(得分:1)

好吧,您要将字节 Java 发布到 C#。问题是Java字节的范围 在-128到127 之间,而C#字节的范围是 从0到255 。当您从Java发布字节时,他们将序列化转换为JSON字符串([&#39; -128&#39;,&#39; -30&#39;,&#39; 127&#39;]您的WebApi控制器接收它们并尝试反序列化它们为C#字节(范围从0到255)。不幸的是,由于负数,它失败了。所以你必须正确反序列化。

选项1:在控制器中使用sbyte

在WebApi中,将模型更改为:

public class Visit 
{
    public int VisitId;
    public String DealerMId;
    public sbyte[] Image; // only for C#
}

WebApi控制器将数组成功反序列化为sbyte(范围:-128到127),然后您可以轻松地将它们转换为字节(取自SO answer):< / p>

byte[] imageBytes = (byte[]) (Array)myVisitModel.Image; 

选项2:从Java

发送int[]

将您的字节发送为 int [] ,以便发送范围为0到255 的字节。

将您的Java模型更改为:

public class Visit {
    public int VisitId;
    public String DealerMId;
    public int[] Image;
}

将byte []转换为int []:

byte[] imageBytes = c.getBlob(c.getColumnIndex(KEY_PICTURE));
visit.Image= convertToIntArray(imageBytes);

转换方法(taken from Jon Skeet's answer):

public static int[] convertToIntArray(byte[] input)
{
    int[] ret = new int[input.length];
    for (int i = 0; i < input.length; i++)
    {
        ret[i] = input[i] & 0xff; // Range 0 to 255, not -128 to 127
    }
    return ret;
}

注意:我推荐第一个选项,它将在服务器端上完成,而第二个选项可能需要转换为客户端上的int[]

答案 1 :(得分:0)

你可以使用JsonSerializer(用Kotlin编写):

class ByteArrayJsonSerializer : JsonSerializer<ByteArray> {

    override fun serialize(src: ByteArray?, typeOfSrc: Type?, context: JsonSerializationContext?): JsonElement {
        val intArray = JsonArray()
        src?.forEach { intArray.add(it.toInt() + 128) }
        return intArray
    }
}

并添加到你的Gson:

GsonBuilder()
            .registerTypeAdapter(ByteArray::class.java, ByteArrayJsonSerializer())  // to convert java Byte to C# Byte
            .create()