我正在尝试将一些数据发送到服务器.服务器正在等待json和图像.我尝试了我找到的每个例子,但我无法发送数据.实际上我正在发送带有PrintWriter对象的json params,但它不接受图像.我需要使用HttpURLConnection而不是apache库.这是我的一段代码:
HttpURLConnection connection = null;
PrintWriter output = null;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
attachImage.compress(Bitmap.CompressFormat.PNG, 40, stream);
byte[] imageData = stream.toByteArray();
String imagebase64 = Base64.encodeToString(imageData, Base64.DEFAULT);
Log.d(tag, "POST to " + url);
try{
URL url = new URL(this.url);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestProperty(HTTP_CONTENT_TYPE, "application/json; charset=utf-8");
connection.setRequestProperty(HTTP_USER_AGENT, mUserAgent);
connection.setRequestProperty(HTTP_HEADER_ACCEPT, "application/json; charset=utf-8");
connection.connect();
output = new PrintWriter(connection.getOutputStream());
JSONObject jsonParam = new JSONObject();
jsonParam.put("oauth_token", params.get("oauth_token"));
jsonParam.put("rating", "1");
jsonParam.put("comments", "ASDASDASDASDASDASDAS");
Log.d(tag, jsonParam.toString());
output.print(jsonParam);
output.flush();
output.close();
Log.d(tag, connection.getResponseCode() + connection.getResponseMessage());
}catch(Exception e ){
}
当我尝试在json params中发送图像时,我收到500内部错误消息.
谢谢!
最佳答案 好的,根据我的建议2种方式将图像发送到服务器
>使用base 64字符串
>直接上传到服务器
1.for base 64转到下面的链接
Android post Base64 String to PHP
2.直接上传到服务器请检查以下链接
快乐的编码!!