gpt4 book ai didi

Android httpPost 带参数和文件

转载 作者:IT老高 更新时间:2023-10-28 21:59:26 26 4
gpt4 key购买 nike

我需要上传一些数据到 PHP 服务器。我可以用参数发帖:

String url = "http://yourserver";

HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
nameValuePairs.add(new BasicNameValuePair("user", "username"));
nameValuePairs.add(new BasicNameValuePair("password", "password"));
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpClient.execute(httpPost);
}

我也可以上传文件:

String url = "http://yourserver";
File file = new File(Environment.getExternalStorageDirectory(),
"yourfile");
try {
HttpClient httpclient = new DefaultHttpClient();

HttpPost httppost = new HttpPost(url);

InputStreamEntity reqEntity = new InputStreamEntity(
new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true); // Send in multiple parts if needed
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
//Do something with response...
}

但是我怎样才能把它放在一起呢?我需要在一篇文章中上传图片和参数。谢谢

最佳答案

您必须使用 MultipartEntity。在线查找并下载这两个库:httpmime-4.0.jarapache-mime4j-0.4.jar,然后您可以根据需要附加任意数量的内容。以下是如何使用它的示例:

HttpPost httpost = new HttpPost("URL_WHERE_TO_UPLOAD");
MultipartEntity entity = new MultipartEntity();
entity.addPart("myString", new StringBody("STRING_VALUE"));
entity.addPart("myImageFile", new FileBody(imageFile));
entity.addPart("myAudioFile", new FileBody(audioFile));
httpost.setEntity(entity);
HttpResponse response;
response = httpclient.execute(httpost);

对于服务器端,您可以使用这些实体标识符名称 myImageFilemyStringmyAudioFile

关于Android httpPost 带参数和文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13002547/

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