gpt4 book ai didi

java - 如何解析多部分/表单数据?

转载 作者:IT王子 更新时间:2023-10-29 02:19:43 26 4
gpt4 key购买 nike

我有一个用 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
}

}

Android 的 Java 客户端代码:

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. 也许我可以使用一些库来做到这一点?

帮助将不胜感激

最佳答案

首先,我建议您使用包装器库来管理网络连接,因为它需要一些经验才能以正确的方式处理它们。我不建议您使用 HttpURLConnection

手动制作 multipart 请求

安卓

你可以尝试使用OkHTTP甚至 Retrofit ,如果您不想手动配置连接。

OKHTTP

这里是一个基本的例子,我省略了一些像异常处理这样的部分。另请注意,您无需为每次调用都创建客户端。

OkHttpClient client = new OkHttpClient.Builder().build();
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("image_file", imageFileName, RequestBody.create(
MediaType.parse("image/jpeg"), new File(pathToImage)));
.addFormDataPart("anyOtherFormArg", arg1)
.addFormDataPart("anotherArg", arg2)
.build();
Request request = new Request.Builder().url(url).post(body).build();
Response response = client.newCall(request).execute();
result = response.body().string();

改造

Retrofit 只是用漂亮的界面包装底层网络请求

@Multipart
@POST("endpoint/image")
Observable<ResponseBody> uploadImage(@Part("arg1") RequestBody arg1,
@Part MultipartBody.Part image);

Go 服务器

在服务器端你可以尝试使用

func uploadHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
err := r.ParseMultipartForm(32 << 20) // 32MB max upload size
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
m := r.MultipartForm
var file_name string
file, handler, err := r.FormFile("image_file")//get file
defer file.Close() //close the file when we finish
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
f, err := os.OpenFile("/path_to_save_image/"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
file_name = handler.Filename
defer f.Close()
io.Copy(f, file)

//return something
w.Header().Set("Content-Type", "application/json")
w.Write("success")
w.WriteHeader(200)
}
w.Header().Set("Content-Type", "application/json")
w.Write("error")
w.WriteHeader(400)
}

这只是一个基本示例,请尝试理解每个部分并根据需要对其进行调整。

关于java - 如何解析多部分/表单数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54721548/

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