从Android应用程序将byte []作为参数传递给JSON服务 [英] Pass byte[] as parameter to JSON service from Android Application
问题描述
大家好,
我试图从Android应用程序将byte []传递给JSON服务,但收到一条错误消息不允许".
我正在使用的服务方法:
Hi All,
I am trying to pass byte[] to JSON Service from the Android App but I am getting an error message "not allowed".
Service Method I am using :
[OperationContract]
[WebGet( RequestFormat=WebMessageFormat.Json,
ResponseFormat=WebMessageFormat.Json,
UriTemplate = "/uploadImage?data={data}&emailID={emailID}")]
bool uploadImage(byte[] data, string emailID);
配置文件端点:
The config file endpoints:
<services>
<service behaviorConfiguration="WebServiceBehaviour" name="WcfService.Service1">
<endpoint address="" behaviorConfiguration="jsonBehavior" binding="webHttpBinding" bindingConfiguration="webHttpBindingWithJsonP" contract="WcfService.IService1"></endpoint>
<endpoint address="soap" binding="basicHttpBinding" contract="WcfService.IService1"></endpoint>
</service>
</services>
Android应用程式代码:
Android app code :
private String GetLocationInfo() {
String loc="";
try {
bm = BitmapFactory.decodeResource(getResources(),R.drawable.testtmage);
bos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 40 , bos);
bitmapdata=bos.toByteArray();
String imgData=Base64.encodeToString(bitmapdata,Base64.DEFAULT);
String img=imgData.replace("\n", "%20");
// Send GET request to <service>/GetPlates
String url=SERVICE_URI + "/uploadImage?data=bitmapdata&emailID=acp@own.com";
HttpGet request = new HttpGet();
request.setURI(new URI(url));
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
HttpEntity responseEntity = response.getEntity();
// Read response data into buffer
char[] buffer = new char[(int)responseEntity.getContentLength()];
InputStream stream = responseEntity.getContent();
InputStreamReader reader = new InputStreamReader(stream);
reader.read(buffer);
stream.close();
//JSONArray plates = new JSONArray(new String(buffer));
for (int i = 0; i < buffer.length; i++) {
loc+=buffer[i];
}
} catch (Exception e) {
e.printStackTrace();
}
return loc;
}
如果还有其他解决方案将图像字节从android传递到JSON Wcf服务,请提出建议.
我对Java编码不太熟悉,非常感谢您的帮助.
预先感谢,
--Avinash
If there is any other solution to pass image bytes from android to JSON Wcf service please suggest.
I am not much familiar with java coding, your help is much appreciated.
Thanks in advance,
--Avinash
推荐答案
这是服务实现:
Hi ,
Here is the service implementation:
<pre lang="cs">[OperationContract]
[WebInvoke(Method="POST", RequestFormat = WebMessageFormat.Xml,
ResponseFormat = WebMessageFormat.Xml,
UriTemplate = "/TestMethod")]
bool TestMethod(CustomImage cust);
用户定义的数据类型:
User defined data type:
[DataContract]
public class CustomImage
{
[DataMember]
public string fileName { get; set; }
[DataMember]
public string[] ImageBytes { get; set; }
[DataMember]
public string EmailID { get; set; }
public string DateOfBirth { get; set; }
}
将string []转换为c#中的图像:
Convert string[]to Image in c#:
try
{
byte[] total_size = new byte[data.Length];
List<byte> bytes = new System.Collections.Generic.List<byte>();
foreach (string str in data)
{
//combine image bytes
byte[] imageBytes = Convert.FromBase64String(str);
bytes.AddRange(imageBytes);
}
Utils.FlowLog.getInstance().Log("Total size" + bytes.Count);
byte[] bary = bytes.ToArray();
byte[] imagebytes = bary;
string fName1 =fileName;
if (File.Exists(fName1) == true)
{
File.Delete(fName1);
}
using (FileStream sw = File.Open(fName1, FileMode.Create))
{
sw.Write(imagebytes, 0, imagebytes.Length);
sw.Close();
}
return true;
}
catch (Exception ex)
{
//exception logger
return false;
}
谢谢,
Avinash
Thanks,
Avinash
您不能直接传递字节,不能将字节流转换为BASE64编码的字符串并传递它.
You cant directly pass the bytes,convert the byte stream to BASE64 encoded string and pass it.
大家好,
这是我将值从android发送到JSON WCF SERVICE的操作:
WCF服务方法声明:
Hi All,
This what I did to send values to JSON WCF SERVICE from android:
Wcf service method declaration:
[OperationContract]
[WebInvoke(Method="POST", RequestFormat = WebMessageFormat.Xml,
ResponseFormat = WebMessageFormat.Xml,
UriTemplate = "/TestMethod")]
bool TestMethod(CustomImage cust);
此功能提供要上传的图像字节数组-
This function is giving the array of bytes of image to be uploading -
public JSONArray readBytes(InputStream inputStream) throws IOException, JSONException {
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
JSONArray array=new JSONArray();
int len = 0,i=0;
while ((len = inputStream.read(buffer)) != -1) {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
byteBuffer.write(buffer, 0, len);
byte[] b= byteBuffer.toByteArray();
array.put(i,Base64.encodeToString(b, Base64.DEFAULT));
i++;
}
return array;
}
以下是将类对象传递给JSON WCF服务的方法:
Following is the way to pass class object to JSON WCF Service :
try
{
InputStream is = new BufferedInputStream (getResources().openRawResource(R.drawable.gtan));
JSONArray array=readBytes(is);
is.close();
URI uri = new URI(SERVICE_URI+ "/TestMethod");
JSONObject jo1 = new JSONObject();
jo1.put("fileName", "avi.jpg");
jo1.put("ImageBytes",array); // assign value to string[]
jo1.put("EmailID", "avinash1234@gmail.com");
jo1.put("SkinCareInterest", "Acne");
jo1.put("LightSource", "Sunny");
jo1.put("SkinType", "3");
jo1.put("DateOfBirth", "1987-09-15");
jo1.put("UserName", "BTBP");
jo1.put("Password", "BTBP");
HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection();
conn.setConnectTimeout(5*1000*3600); //set time out
conn.setReadTimeout(5*1000*3600); // set socket time out
conn.setRequestProperty("Content-Type","application/json; charset=utf-8");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("User-Agent", "Pigeon");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.connect();
OutputStream os =conn.getOutputStream();
DataOutputStream out = new DataOutputStream(os);
out.write(jo1.toString().getBytes());
out.flush();
os.close();
int code = conn.getResponseCode();
String message = conn.getResponseMessage();
conn.disconnect();
}
catch(Exception ex)
{
ex.printStackTrace();
}
谢谢,
阿维纳什·帕蒂尔(Avinash Patil)
Thanks,
Avinash Patil
这篇关于从Android应用程序将byte []作为参数传递给JSON服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!