[英]Uploading files and other data from Android through Http POST request
這是從Android發布文件的簡單方法。
String url = "http://yourserver.com/upload.php";
File file = new File("myfileuri");
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...
} catch (Exception e) {
e.printStackTrace();
}
我想要做的是在我的請求中添加更多POST
變量。 我怎么做? 在POST
請求中上傳純字符串時,我們使用URLEncodedFormEntity
。
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
而在上傳文件時,我們使用InputStreamEntity
。
另外,如何將此文件專門上傳到$_FILES['myfilename']
?
最有效的方法是使用android-async-http
您可以使用此代碼上傳文件:
File myFile = new File("/path/to/file.png");
RequestParams params = new RequestParams();
try {
params.put("profile_picture", myFile);
} catch(FileNotFoundException e) {}
花了一整天后找到了loopj 。 您可以關注此代碼示例:
//context: Activity context, Property: Custom class, replace with your pojo
public void postProperty(Context context,Property property){
// Creates a Async client.
AsyncHttpClient client = new AsyncHttpClient();
//New File
File files = new File(property.getImageUrl());
RequestParams params = new RequestParams();
try {
//"photos" is Name of the field to identify file on server
params.put("photos", files);
} catch (FileNotFoundException e) {
//TODO: Handle error
e.printStackTrace();
}
//TODO: Reaming body with id "property". prepareJson converts property class to Json string. Replace this with with your own method
params.put("property",prepareJson(property));
client.post(context, baseURL+"upload", params, new AsyncHttpResponseHandler() {
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
System.out.print("Failed..");
}
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
System.out.print("Success..");
}
});
}
幾種方式:
發2個帖子請求:首先使用圖像文件。 服務器返回一個圖像ID,第二個請求你附加到這個id你的參數。
或者,您可以使用MultipartEntity
請求代替“2請求”解決方案。 在這里查看更多數據
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.