Android 尝试使用截击发送图像文件时出错?
我有一个图像,我正试图与其他参数一起使用Volley库发送到我的web服务。问题是我不知道如何使用POST传递有关url的图像 寻找一个解决方案,我发现了任何使用MultiPart的建议,我正在尝试实现它,但仍然无法做到这一点 我在我的应用程序中创建了另一个构造函数,这个构造函数应该接收一个文件,但也不工作,HashMap不接受文件参数 我该怎么做 我正在试这个Android 尝试使用截击发送图像文件时出错?,android,android-volley,Android,Android Volley,我有一个图像,我正试图与其他参数一起使用Volley库发送到我的web服务。问题是我不知道如何使用POST传递有关url的图像 寻找一个解决方案,我发现了任何使用MultiPart的建议,我正在尝试实现它,但仍然无法做到这一点 我在我的应用程序中创建了另一个构造函数,这个构造函数应该接收一个文件,但也不工作,HashMap不接受文件参数 我该怎么做 我正在试这个 public class ApplicationController extends Request<JSONObject>
public class ApplicationController extends Request<JSONObject>{
private Map<String, String> headers;
private Map<String, String> params;
private Response.Listener<JSONObject> listener;
private File imageFile;
private MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create();
public ApplicationController(String url, Map<String, String> params, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(Method.GET, url, errorListener);
this.listener = listener;
this.params = params;
}
public ApplicationController(int method, String url, Map<String, String> params, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(method, url, errorListener);
this.listener = listener;
this.params = params;
}
/** construtor to send image */
public ApplicationController(int method,
String url,
Map<String, String> params,
Response.Listener<JSONObject> listener,
Response.ErrorListener errorListener,
File file) {
super(method, url, errorListener);
this.listener = listener;
this.params = params;
this.imageFile = file;
}
protected Map<String, String> getParams() throws AuthFailureError {
return params;
};
public Map<String, String> getHeaders() throws AuthFailureError {
headers = new HashMap<String, String>();
String cred = String.format("%s:%s", BasicAuthenticationRest.USERNAME, BasicAuthenticationRest.PASSWORD);
String auth = "Basic " + Base64.encodeToString(cred.getBytes(), Base64.DEFAULT);
headers.put("Authorization", auth);
return headers;
};
private void buildMultipartEntity(){
mBuilder.addBinaryBody("", imageFile, ContentType.create("image/png"), imageFile.getName());
mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
mBuilder.setLaxMode().setBoundary("xx").setCharset(Charset.forName("UTF-8"));
}
@Override
public String getBodyContentType(){
String contentTypeHeader = mBuilder.build().getContentType().getValue();
return contentTypeHeader;
}
@Override
public byte[] getBody() throws AuthFailureError{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try{
mBuilder.build().writeTo(bos);
}catch (IOException e){
VolleyLog.e("IOException writing to ByteArrayOutputStream bos, building the multipart request.");
}
return bos.toByteArray();
}
@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString), HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
@Override
protected void deliverResponse(JSONObject response) {
listener.onResponse(response);
}
}
公共类应用程序控制器扩展请求{
私有映射头;
私有映射参数;
私人回应。倾听者;
私有文件;
私有MultipartEntityBuilder mBuilder=MultipartEntityBuilder.create();
公共应用程序控制器(字符串url、映射参数、Response.Listener、Response.ErrorListener ErrorListener){
super(Method.GET、url、errorListener);
this.listener=listener;
this.params=params;
}
公共应用程序控制器(int方法、字符串url、映射参数、Response.Listener、Response.ErrorListener){
super(方法、url、errorListener);
this.listener=listener;
this.params=params;
}
/**construtor发送图像*/
公共应用程序控制器(int方法,
字符串url,
映射参数,
回应,听众,
Response.ErrorListener ErrorListener,
(文件){
super(方法、url、errorListener);
this.listener=listener;
this.params=params;
this.imageFile=文件;
}
受保护的映射getParams()引发AuthFailureError{
返回参数;
};
公共映射getHeaders()引发AuthFailureError{
headers=newhashmap();
String cred=String.format(“%s:%s”,BasicAuthenticationRest.USERNAME,BasicAuthenticationRest.PASSWORD);
字符串auth=“Basic”+Base64.encodeToString(cred.getBytes(),Base64.DEFAULT);
headers.put(“授权”,auth);
返回标题;
};
私有void buildMultipartEntity(){
mBuilder.addBinaryBody(“”,imageFile,ContentType.create(“image/png”),imageFile.getName());
mBuilder.setMode(HttpMultipartMode.BROWSER_兼容);
mBuilder.setLaxMode().setBoundary(“xx”).setCharset(Charset.forName(“UTF-8”));
}
@凌驾
公共字符串getBodyContentType(){
字符串contentTypeHeader=mBuilder.build().getContentType().getValue();
返回contentTypeHeader;
}
@凌驾
公共字节[]getBody()抛出AuthFailureError{
ByteArrayOutputStream bos=新建ByteArrayOutputStream();
试一试{
mBuilder.build().writeTo(bos);
}捕获(IOE异常){
e(“IOException写入ByteArrayOutputStream bos,构建多部分请求”);
}
返回bos.toByteArray();
}
@凌驾
受保护的响应parseNetworkResponse(NetworkResponse响应){
试一试{
String jsonString=新字符串(response.data,HttpHeaderParser.parseCharset(response.headers));
返回Response.success(新的JSONObject(jsonString),HttpHeaderParser.parseCacheHeaders(Response));
}捕获(不支持的编码异常e){
返回Response.error(新的ParseError(e));
}捕获(JSONException je){
返回Response.error(newparseerror(je));
}
}
@凌驾
受保护的void deliverResponse(JSONObject响应){
onResponse(response);
}
}
使用
/** add an user and upload your foto(image) */
public ApplicationController insert(Usuario u, File imageFile, final UsuarioAdapter listener){
boolean insert = false;
HashMap<String, String> params = new HashMap<String, String>();
params.put("nome", u.getNome());
params.put("email", u.getEmail());
params.put("senha", u.getSenha());
params.put("tipo", "usuarios");
params.put("acao", "add");
params.put("device_tipo", "android");
params.put("device", AndroidReturnId.getAndroidId());
params.put("uploadedfile", imageFile);
ApplicationController apc = new ApplicationController(Method.POST, urlPost.toString(), params,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject obj) {
try {
if(obj.getString("cod").equals("999")){
listener.usuarioIsAdded(true);
}else{
listener.usuarioIsAdded(false);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError arg0) {
Log.e("ERROR METHOD:", "insert in UsuarioDAO: " + arg0.getLocalizedMessage());
}
}, File file);
return apc;
}
/**添加用户并上传您的foto(图像)*/
公共应用程序控制器插入(Usuario u、文件imageFile、最终Usuario适配器侦听器){
布尔插入=假;
HashMap params=新的HashMap();
参数put(“nome”,u.getNome());
参数put(“email”,u.getEmail());
参数put(“senha”,u.getSenha());
参数put(“tipo”、“usuarios”);
参数put(“acao”、“add”);
参数put(“设备_tipo”、“安卓”);
参数put(“设备”,AndroidReturnId.getAndroidId());
参数put(“uploadedfile”,imageFile);
ApplicationController apc=新的ApplicationController(Method.POST,urlPost.toString(),params,
新建响应。侦听器(){
@凌驾
公共void onResponse(JSONObject obj){
试一试{
如果(obj.getString(“cod”).equals(“999”){
listener.usuarioIsAdded(true);
}否则{
listener.usuarioIsAdded(false);
}
}捕获(JSONException e){
e、 printStackTrace();
}
}
},
新的Response.ErrorListener(){
@凌驾
公共错误响应(截击错误arg0){
Log.e(“错误方法:”,“在UsuarioDAO中插入:”+arg0.getLocalizedMessage());
}
},档案);
返回apc;
}
将文件编码为base 64编码字符串,并在正文中进行设置(只需确保您的服务器接受此格式!)。谷歌如何在java中做到这一点
params.put("uploadedfile", base64EncodedImageFile);