gpt4 book ai didi

android - 在 android 中使用 HttpURLConnection 发送 JSON 和图像

转载 作者:太空宇宙 更新时间:2023-11-03 10:18:39 24 4
gpt4 key购买 nike

我正在尝试向服务器发送一些数据。服务器正在等待 json 和图像。我尝试了我发现的每个例子,但我无法发送数据。实际上我正在发送带有 PrintWriter 对象的 json 参数,但它不接受图像。 我需要将 HttpURLConnection 与 apache 库一起使用。这是我的一段代码:

HttpURLConnection connection = null;
PrintWriter output = null;

ByteArrayOutputStream stream = new ByteArrayOutputStream();
attachImage.compress(Bitmap.CompressFormat.PNG, 40, stream);
byte[] imageData = stream.toByteArray();
String imagebase64 = Base64.encodeToString(imageData, Base64.DEFAULT);

Log.d(tag, "POST to " + url);
try{
URL url = new URL(this.url);
connection = (HttpURLConnection) url.openConnection();

connection.setRequestMethod("POST");

connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);

connection.setRequestProperty(HTTP_CONTENT_TYPE, "application/json; charset=utf-8");
connection.setRequestProperty(HTTP_USER_AGENT, mUserAgent);
connection.setRequestProperty(HTTP_HEADER_ACCEPT, "application/json; charset=utf-8");
connection.connect();
output = new PrintWriter(connection.getOutputStream());

JSONObject jsonParam = new JSONObject();
jsonParam.put("oauth_token", params.get("oauth_token"));
jsonParam.put("rating", "1");
jsonParam.put("comments", "ASDASDASDASDASDASDAS");


Log.d(tag, jsonParam.toString());

output.print(jsonParam);
output.flush();
output.close();

Log.d(tag, connection.getResponseCode() + connection.getResponseMessage());
}catch(Exception e ){

}

当我尝试在 json 参数中发送图像时,收到 500 内部错误消息。

谢谢!

最佳答案

好的,按照我的建议,将图像发送到服务器的 2 种方法

  1. 使用base 64字符串
  2. 直接上传到服务器

1.对于 base 64 转到下面的链接

Android post Base64 String to PHP

2.直接上传到服务器请检查下面的链接

http://www.androidhive.info/2014/12/android-uploading-camera-image-video-to-server-with-progress-bar/

编码愉快!!

关于android - 在 android 中使用 HttpURLConnection 发送 JSON 和图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30052969/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com