安卓使用WCF的Restful方式上传文件

//安卓部分的代码
public class UploadFile {

	public static void toUploadFile(String url, String path) throws FileNotFoundException {
		try {
			// 1,读出文件到byte[]
			InputStream is = new FileInputStream(path);
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			byte[] buff = new byte[1024]; // buff用于存放循环读取的临时数据
			int rc = 0;
			while ((rc = is.read(buff, 0, 1024)) > 0) {
				os.write(buff, 0, rc);
			}
			ByteArrayEntity reqEntity = new ByteArrayEntity(os.toByteArray());
			reqEntity.setContentType("binary/octet-stream");
			reqEntity.setChunked(true);

			// 2, 初始化Post, 添加参数
			HttpPost httpPost = new HttpPost(url);
			httpPost.setHeader("charset", HTTP.UTF_8);
			httpPost.setHeader("Accept", "application/json");
			httpPost.setHeader("Content-Type", "binary/octet-stream");
			httpPost.setEntity(reqEntity);

			DefaultHttpClient client = getHttpClient();
			HttpResponse response = client.execute(httpPost);// 上传文件

			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == 200) {
				System.out.println("调用成功: statusCode : " + statusCode);
				return;
			} else {
				System.out.println("调用失败:code=" + statusCode);
				return;
			}
		} catch (ClientProtocolException e) {
			System.out.println(e.toString());
		} catch (IOException e) {
			System.out.println(e.toString());
		} catch (Exception e) {
			System.out.println(e.toString());
		}
	}

	protected static DefaultHttpClient getHttpClient() {
		DefaultHttpClient client = new DefaultHttpClient();
		client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 300);// 连接时间
		client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 3600 * 1000);// 超时时间
		return client;
	}
}


//WCF部分的代码
[WebInvoke(UriTemplate = "ReceiveImg2", Method = "POST")]
public string ReceiveImg2(Stream request)
{
	try
	{
		string path = System.Web.Hosting.HostingEnvironment.MapPath("~") + "1.jpg";
		using (var file = File.Create(path))
		{
			request.CopyTo(file);
		}
		return "1";
	}
	catch
	{
		return "-1";
	}
}


web.Config里面 basicHttpBinding 的配置
<basicHttpBinding>
	<binding name="DocumentExplorerServiceBinding"
			 sendTimeout="00:10:00"
			 transferMode="Streamed"
			 messageEncoding="Text"
			 textEncoding="utf-8"
			 maxReceivedMessageSize="9223372036854775807">
	</binding>
</basicHttpBinding>

猜你喜欢

转载自zheyiw.iteye.com/blog/2195105