这就是我如何让它为那些将来可能会发现它的人工作的。
对于这个例子,假设我们要使用参数t=ABC123 和id=12 在www.server.com 的根目录上查询PHP 脚本upload.php。除了这个请求,我们还想上传存储在java.io.File 对象img 中的图像。我们还将期待服务器的响应,让我们知道上传是否成功。
安卓端
在 android 端,您将需要以下 JAR:
apache-mime4j-core-0.7.2.jar
可用here 和:
httpclient-4.3.1.jar
httpcore-4.3.jar
httpmime-4.3.1.jar
可用here。
这是一个关于如何发出多部分请求并获得响应的 sn-p:
public String uploadRequest(String address, File img)
{
HttpParams p = new BasicHttpParams();
p.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
DefaultHttpClient client = new DefaultHttpClient(p);
HttpPost post = new HttpPost(address);
// No need to add regular params as parts. You can if you want or
// you can just tack them onto the URL as usual.
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("image", new FileBody(img));
post.setEntity(builder.build());
return client.execute(post, new ImageUploadResponseHandler()).toString();
}
private class ImageUploadResponseHandler implements ResponseHandler<Object>
{
@Override
public Object handleResponse(HttpResponse response) throws ClientProtocolException, IOException
{
HttpEntity responseEntity = response.getEntity();
return EntityUtils.toString(responseEntity);
}
}
在代码中使用此方法的示例(假设变量img 已声明包含您要上传的图像的File 对象):
// Notice regular params can be included in the address
String address = "http://www.server.com/upload.php?t=ABC123&id=12";
String resp = uploadRequest(address, img);
// Handle response
PHP 端
对于服务端脚本,文本参数可以通过PHP的$_REQUEST对象正常访问:
$token = $_REQUEST['token'];
$id = $_REQUEST['id'];
上传的图片可以通过存储在 PHP $_FILES 对象中的信息来访问(更多信息请参见 PHP 文档):
$img = $_FILES['img'];