我在C#中实现了REST服务来上传图像:
[OperationContract]
[WebInvoke(Method = "PUT", UriTemplate = "add/{idAlbum}/{name}/image")]
void Add(string idAlbum, string name, Stream image);
我已成功将其与C#客户端一起使用:
byte[] image = lireFichier(@"C:\Users\user\Pictures\asap2.jpeg");
WebClient client = new WebClient();
client.Headers.Add("Content-Type", "image/jpeg");
var results = client.UploadData("http://localhost:1767/ImageService.svc/add/1/REST/image", "PUT", image);
所以现在我想用它像这样的Java客户端(android)(不工作):
HttpURLConnection conn = ( HttpURLConnection ) new URL( "http://localhost:1767/ImageService.svc/add/1/RESTjava/image" ).openConnection();
conn.setRequestMethod("PUT");
conn.setDoOutput( true );
conn.connect();
OutputStream out = conn.getOutputStream();
Bitmap img = ((BitmapDrawable)getResources().getDrawable(R.drawable.entourage)).getBitmap();
ByteArrayOutputStream bao = new ByteArrayOutputStream();
img.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte[] data = bao.toByteArray();
out.write(data);
我没有任何错误,但这不起作用。没有例外。
06-05 14:11:57.736: I/ASAP PICS(746): onPreExecute
06-05 14:11:57.745: I/ASAP PICS(746): doInBackground
06-05 14:11:57.816: I/System.out(746): 405
06-05 14:44:26.245: D/dalvikvm(971): GC freed 238 objects / 332400 bytes in 34ms
06-05 14:11:57.905: I/ASAP PICS(746): onPostExecute
答案 0 :(得分:0)
您应该flush
:OutputStream
out.flush();
。这就是答案。
答案 1 :(得分:0)
I / System.out(746):405
HTTP 405 =不允许使用方法。
我想你必须添加身份验证吗?
答案 2 :(得分:0)
我找到了解决方案!
首先,我将REST服务放在POST方法中:
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "add/{idAlbum}/{name}")]
void Add(string idAlbum, string name, Stream image);
最后是java客户端:
HttpPost post = new HttpPost("http://localhost:1767/ImageService.svc/add/1/RESTjava");
Bitmap img = ((BitmapDrawable)getResources().getDrawable(R.drawable.entourage)).getBitmap();
ByteArrayOutputStream bao = new ByteArrayOutputStream();
img.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte[] data = bao.toByteArray();
ByteArrayEntity bimg = new ByteArrayEntity(data);
post.setEntity(bimg);
new DefaultHttpClient().execute(post);