4
我想將圖像上傳到PHP頁面以及有關圖像的其他信息,以便PHP頁面知道如何處理它。目前,我越來越使用它:Android:將文件與其他POST字符串一起上傳到頁面
URL url = new URL("http://www.tagverse.us/upload.php?authcode="+WEB_ACCESS_CODE+"&description="+description+"&userid="+userId);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
OutputStream os = connection.getOutputStream();
InputStream is = mContext.getContentResolver().openInputStream(uri);
BufferedInputStream bis = new BufferedInputStream(is);
int totalBytes = bis.available();
for(int i = 0; i < totalBytes; i++) {
os.write(bis.read());
}
os.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String serverResponse = "";
String response = "";
while((response = reader.readLine()) != null) {
serverResponse = serverResponse + response;
}
reader.close();
bis.close();
是否有一個更優雅的解決方案,除了有一個GET/POST混合?我覺得這是蠻橫的,但我知道這是一個完全可以接受的解決方案。如果有更好的方法來做到這一點,我會很高興指出正確的方向。謝謝!
PS:我所熟悉的你會如何,在正常情況下,一個PHP頁面通過POST互動:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.tagverse.us/login.php");
try {
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("authcode", WEB_ACCESS_CODE));
pairs.add(new BasicNameValuePair("username", username));
pairs.add(new BasicNameValuePair("password", password));
post.setEntity(new UrlEncodedFormEntity(pairs));
client.execute(post);
}
基本上我想要做的就是這兩種方法結合起來的東西,而是因爲我使用HttpURLConnection對象而不是HttpPost對象,並不像合併兩者那麼簡單。
謝謝!