为了账号安全,请及时绑定邮箱和手机立即绑定

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

标签:
Python

概述

在使用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

总结

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

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消