【发布时间】:2019-02-16 09:12:29
【问题描述】:
我有一个用Go写的服务器。
基本上,它接收 POST 请求并以 multipart/form-data 的形式发送一些文件作为响应。
以下是服务器代码:
func ColorTransferHandler(w http.ResponseWriter, r *http.Request) {
... some routine...
w.WriteHeader(http.StatusOK)
mw := multipart.NewWriter(w)
filename := "image_to_send_back.png"
part, err := mw.CreateFormFile("image", filename)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
local_file, err := os.Open(filename)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
local_file_content, err := ioutil.ReadAll(local_file)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
part.Write(local_file_content)
w.Header().Set("Content-Type", mw.FormDataContentType())
if err := mw.Close(); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
Java 中用于 Android 的客户端代码:
public class ConnectionUtility {
private final String boundary;
private static final String LINE_FEED = "\r\n";
private HttpURLConnection httpConn;
private String charset;
private OutputStream outputStream;
private PrintWriter writer;
public List<String> finish() throws IOException {
// ...
// content filling
// ...
writer.append(LINE_FEED).flush();
writer.append("--" + boundary + "--").append(LINE_FEED);
writer.close();
List<String> response = new ArrayList<String>();
// checks server's status code first
int status = httpConn.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
response.add(line);
}
reader.close();
httpConn.disconnect();
} else {
throw new IOException("Server returned non-OK status: " + status);
}
return response;
}
以下是我的问题:
1.如何编辑此功能以获取该图像文件并将其保存在驱动器上?
2. 或许我可以使用一些库来做到这一点?
我们将不胜感激
【问题讨论】:
-
在标头已经发送后调用
Header().Set无效。
标签: java android http go multipartform-data