lua发送带图片的帖子(水仙后台)

概述

在使用lua对接水仙后台时,发现通过自带的网络模块http.upload上传图片,发布的帖子只有文字信息,图片显示不了,在使用iapp发送网络请求之后,帖子的图片可以正常显示。

问题分析

由于都是网络请求,我们可以使用HttpCanary(黄鸟)抓包的方式,查看不同应用请求的区别。

  • lua发送请求

Screenshot_2023-04-18-11-56-05-257_com

  • iapp发送请求

Screenshot_2023-04-18-12-00-10-565_com

查看请求可以发现,lua请求的时候,Content-Type为application/octet-stream,iapp请求的时候Content-Type为image/jpeg,这个估计水仙后端对文件的类型做了限制,导致以二进制方式上传后图片显示异常。

解决办法

我们可以使用自带的okhttp发送请求,在上传的时候将文件的MediaType设置为image/jpeg,完成图片上传。实现代码如下:

function upload(url,datas,files,cookie,ua,header)
  import "com.kn.okhtttp.*"
  import "okhttp3.*"
  import "java.io.File"
  local client=OkTest.newok()

  local request=Request.Builder()
  request.url(url)
  local arr=MultipartBody.Builder()
  arr.setType(MultipartBody.FORM)
  if datas then
    for key,value in pairs(datas) do
       arr.addFormDataPart(key,value)
    end
  end
  if files then
    for name,path in pairs(files) do
       arr.addFormDataPart("file[]",path,RequestBody.create(MediaType.parse("image/jpeg"),File(path)))
    end
  end
  local requestBody=arr.build()
  request.post(requestBody)
  if cookie then
    request.header("Cookie",cookie)
  end
  if ua then
    request.header("User-Agent",ua)
  end
  if header then
    for key,value in pairs(header) do
      request.header(key,value)
    end
  end

  local callz=client.newCall(request.build())
  -- 同步请求
  local response=callz.execute()
  local body=response.body().string()
  local cookie=response.headers("Cookie")
  local code=tostring(response.code())
  local headers=response.headers()
  return body,cookie,code,headers
end


-- 以下为方法测试,如需使用,把上面的方法复制到自己的代码中

url="http://shuixian.ltd/main/api/forum/issue.php"

postdata={
    ["admin"]="512357657",
    ["user"]="123456",
    ["password"]="123456",
    ["title"]="发布带图片的帖子",
    ["content"]="图片帖子内容",
    ["plate_id"]="814"
}

filedata={
    ["image_1"]="/storage/emulated/0/tencent/QQ_Images/686fd89e5a1ae39b.jpg",
    ["image_2"]="/storage/emulated/0/tencent/QQ_Images/b352639ead6da9e.jpg"
}

body,cookie,code,headers=upload(url,postdata,filedata)
print(body)
print(cookie)
print(code)
print(headers)
  • 实现效果如下

Screenshot_2023-04-18-16-41-23-490_com

总结

经过分析问题,找到出现问题的原因,采用其余的方式完成我们的需求。文章中的方法同样适用于水仙其它带图片文件的接口。

本文由【产品经理不是经理】gzh 同步发布,欢迎关注

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值