我正在尝试将图像以及有关该图像的其他一些信息上传到 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 …
我确实使用MultipartEntity将File发送到服务器,它在$_FILES超全局中正确显示
但我还需要填写POST正文以供阅读 php://stdin
我怎样才能做到这一点?
下面的当前片段:
ByteArrayOutputStream bos = new ByteArrayOutputStream(); // stream to hold image
bm.compress(CompressFormat.JPEG, 75, bos); //compress image
byte[] data = bos.toByteArray();
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("REMOTE ADDRESS");
ByteArrayBody bab = new ByteArrayBody(data, "image.jpg");
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE); // is this one causing trouble?
reqEntity.addPart("image", bab); // added image to request
// tried this with no luck
// reqEntity.addPart("", new StringBody("RAW DATA HERE"));
postRequest.setEntity(reqEntity); // set the multipart entity …Run Code Online (Sandbox Code Playgroud)