gpt4 book ai didi

android - 发出大型 REST 请求

转载 作者:行者123 更新时间:2023-11-29 21:57:11 24 4
gpt4 key购买 nike

我有一个无法更改的 REST 服务,它具有上传图像的方法,编码为 Base64 字符串。

问题是图像的大小可以达到 5-10MB,甚至更多。当我尝试在设备上构建这种大小的图像的 Base64 表示时,我遇到了 OutOfMemory 异常。

但是我可以一次编码字节 block (比方说 3000),但这是无用的,因为我需要整个字符串来创建 HttpGet/HttpPost 对象:

DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("www.server.com/longString");
HttpResponse response = client.execute(httpGet);

有没有办法解决这个问题?

编辑:尝试使用 Heiko Rupp 的建议 + android 文档,我在以下行收到异常(“java.io.FileNotFoundException:http://www.google.com”):InputStream in = urlConnection.getInputStream();

    try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);

OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
out.write("/translate".getBytes());

InputStream in = urlConnection.getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(in));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
System.out.println("response:" + total);

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

我错过了什么吗?我需要执行的 GET 请求如下所示:“http://myRESTService.com/myMethod?params=LOOONG-String”,所以我的想法是连接到 http://myRESTService.com/myMethod 然后一次输出长字符串的几个字符。这是正确的吗?

最佳答案

您应该尝试使用 URLConnection 而不是 apache http 客户端,因为这不需要您将要发送的对象保存在内存中,但您可以这样做:

伪代码!

HttpUrlConnection con = restUrl.getConnection();
while (!done) {
byte[] part = base64encode(partOfImage);
con.write (part);
partOfImage = nextPartOfImage();
}
con.flush();
con.close();

在 2.2 之后的 Android 中,Google 也推荐通过 http 客户端使用 URLConnection。参见 DefaultHttpClient 的描述.

您可能想要查看的另一件事是要发送的数据量。通过移动网络传输 10 MB + base64 将花费相当长的时间(即使使用 gzip 压缩,如果服务器端接受它,URLConnection 会透明地启用它)。

关于android - 发出大型 REST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12950559/

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