JMR*_*ies 5 php android file-upload
我正在尝试将图像以及有关该图像的其他一些信息上传到 PHP 页面,以便 PHP 页面知道如何处理它。目前,我正在使用它:
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();
Run Code Online (Sandbox Code Playgroud)
除了 GET/POST 混合之外,还有更优雅的解决方案吗?我觉得这似乎很草率,但据我所知,这是一个完全可以接受的解决方案。如果有更好的方法来做到这一点,我会很感激被指出正确的方向。谢谢!
PS:我熟悉您在正常情况下如何通过 POST 与 PHP 页面交互:
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);
}
Run Code Online (Sandbox Code Playgroud)
基本上我想做的是将这两种方法结合起来,但是因为我使用的是 HttpURLConnection 对象而不是 HttpPost 对象,所以它并不像将两者合并那么简单。
谢谢!
您可以尝试看看我为这个类似问题添加的答案: /sf/answers/630257211/
这是代码:
byte[] data = {10,10,10,10,10}; // better get this from a file or memory
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("server url");
ByteArrayBody bab = new ByteArrayBody(data, "image.jpg");
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("image", bab);
FormBodyPart bodyPart=new FormBodyPart("formVariableName", new StringBody("formValiableValue"));
reqEntity.addPart(bodyPart);
bodyPart=new FormBodyPart("formVariableName2", new StringBody("formValiableValue2"));
reqEntity.addPart(bodyPart);
bodyPart=new FormBodyPart("formVariableName3", new StringBody("formValiableValue3"));
reqEntity.addPart(bodyPart);
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = null;
while((line = in.readLine()) != null) {
System.out.println(line);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1927 次 |
| 最近记录: |