我正在尝试将一些用户输入信息、文本和图像(转换为 base64 字符串)上传到服务器。我正在使用 httpurlconnection 来完成此操作,但性能很慢。图像大小为 600 X 600,上传大约需要 119-125 秒,这很多。这是我的代码 -
public class MyClass implements Runnable {
Thread thread = new Thread(this);
public MyClass(String url_string.......) {
thread.start();
}
@Override
public void run()
{
String response = executeRequest();
parseResponse(response);
}
}
URL url_string = prepareURL(url_string, method);
url = new URL(url_string);
httpUrlConnection = (HttpURLConnection) url.openConnection();
httpUrlConnection.setRequestProperty("Connection", "Keep-Alive");
httpUrlConnection.setConnectTimeout(25000);
httpUrlConnection.setUseCaches(false);
httpUrlConnection.setRequestMethod(method);
//method variable in the above line is just a string constant (GET or POST)
if(method.equalsIgnoreCase(Constants.POST)) {
httpUrlConnection.setDoInput(true);
httpUrlConnection.setDoOutput(true);
}
//toUseJson variable is us just a boolean to determine whether
//we have to set the chunking or fixedstreaming mode,
//based on GET method or POST method
if(toUseJson) {
//httpUrlConnection.setFixedLengthStreamingMode(json_message.getBytes().length);
//httpUrlConnection.setChunkedStreamingMode(1024*8);
httpUrlConnection.setChunkedStreamingMode(0);
}
httpUrlConnection.connect();
System.out.println("start - " + System.currentTimeMillis());
if(toUseJson) {
output_stream = httpUrlConnection.getOutputStream();
BufferedOutputStream buffered_output_stream = new BufferedOutputStream(output_stream);
System.out.println("the bytes to read - " + json_message.getBytes().length);
InputStream is = new ByteArrayInputStream(json_message.getBytes("UTF-8"));
byte[] buffer = new byte[1024*1024];
int count = 0;
System.out.println("middle - " + System.currentTimeMillis());
while((count = is.read(buffer)) != -1) {
System.out.println("count - " + count);
buffered_output_stream.write(buffer, 0, count);
}
output_stream.flush();
}
...........
我正在尝试各种组合来缩短上传时间,但是,它总是需要大约 110-120 秒。json 消息的字节数 - 907237 字节
任何帮助,将不胜感激。谢谢!