php – Android:将文件与其他POST字符串一起上传到页面

我正在尝试将图像上传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();

除了拥有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);
}

基本上我想要做的是组合这两种方法,但因为我使用的是HttpURLConnection对象而不是HttpPost对象,所以它并不像仅仅合并这两种方法那么简单.

谢谢!

解决方法:

您可以尝试查看我为此类似问题添加的答案:
https://stackoverflow.com/a/9003674/472747

这是代码

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);
}

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...