Android 如何将媒体文件发送到wcf rest json服务并获取json格式的字符串返回响应
Android 如何将媒体文件发送到wcf rest json服务并获取json格式的字符串返回响应,android,json,image,wcf,upload,Android,Json,Image,Wcf,Upload,请不要将其标记为重复,因为我已经战斗了很多天,并且已经尝试了很多示例,但无法解决问题,也无法解决问题。我对WCF和android也是新手 因此,我用一些get和post方法创建了一个WCF服务,如下所示 [OperationContract] [WebInvoke(Method = "POST", UriTemplate = "RegisterUser", BodyStyle = WebMessageBodyStyle.WrappedRequest,
请不要将其标记为重复,因为我已经战斗了很多天,并且已经尝试了很多示例,但无法解决问题,也无法解决问题。我对WCF和android也是新手
因此,我用一些get和post方法创建了一个WCF服务,如下所示
[OperationContract]
[WebInvoke(Method = "POST",
UriTemplate = "RegisterUser",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
RequestFormat= WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
ResultSet RegisterUser(string EmailID, string Name,Stream profilepic, string Mobile, long IMEI);
我正在通过android客户端调用此服务方法,如下所示
MainActivity.java
public void doneOnClick(View v) throws FileNotFoundException,
InterruptedException, JSONException {
// Toast toast = new Toast(this);
// gets IMEI of device ID
tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
imei = tm.getDeviceId();
bMap = BitmapFactory.decodeFile(selectedImagePath);
path = SaveImage.writeFileToInternalStorage(getApplicationContext(),
bMap, "UserImage.png");
name = nameV.getText().toString();
mobile = mobileV.getText().toString();
emailID = emailV.getText().toString();
if (name.length() != 0 && mobile.length() != 0 && emailID.length() != 0
&& path.length() != 0) {
SharedPreferences shared = getSharedPreferences(PREFS, 0);
Editor editor = shared.edit();
editor.putString("UserPicPath", path);
editor.putString("UserName", name);
editor.putString("UserMobile1", mobile);
editor.putString("UserEmail", emailID);
editor.putString("IMEI", imei);
editor.commit();
}
JSONArray jsonarr = new JSONArray();
JSONObject jsonObj = new JSONObject();
jsonObj.put("emailID", emailID);
jsonObj.put("name", name);
jsonObj.put("mobile", mobile);
jsonObj.put("imei", imei);
jsonarr.put(jsonObj);
servicemethodname = "RegisterUser";
DownloadWebPageTask bcktask = new DownloadWebPageTask();
bcktask.execute(servicemethodname, jsonarr);
}
并将backgroundtask称为
package com.example.wcfconsumer;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.util.Base64;
import android.util.Log;
public class DownloadWebPageTask extends AsyncTask<Object, Integer, String> {
private final static String SERVICE_URI = "http://192.168.0.100:80/Service1.svc/";
protected void onPostExecute(String result) {
MainActivity.emailV.setText(result);
}
@Override
protected String doInBackground(Object... params) {
JSONArray jsonparams = (JSONArray) params[1];
String methodname = params[0].toString();
InputStream is;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(SERVICE_URI + methodname);
StringEntity se = new StringEntity(jsonparams.toString(), "UTF-8");
se.setContentType("application/json;charset=UTF-8");
httpPost.setEntity(se);
Log.e("Gerhard", jsonparams.toString());
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
InputStreamReader i = new InputStreamReader(is);
BufferedReader str = new BufferedReader(i);
String msg = str.readLine();
Log.e("Gerhard", msg);
return msg;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private String convertToString(Bitmap image) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
String mediaString = Base64.encodeToString(data, Base64.URL_SAFE);
return mediaString;
}
}
package com.example.wcfconsumer;
导入java.io.BufferedReader;
导入java.io.ByteArrayOutputStream;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.io.UnsupportedEncodingException;
导入org.apache.http.HttpEntity;
导入org.apache.http.HttpResponse;
导入org.apache.http.client.ClientProtocolException;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.entity.StringEntity;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.json.JSONArray;
导入android.graphics.Bitmap;
导入android.os.AsyncTask;
导入android.util.Base64;
导入android.util.Log;
公共类下载WebPagetTask扩展异步任务{
私有最终静态字符串服务\u URI=”http://192.168.0.100:80/Service1.svc/";
受保护的void onPostExecute(字符串结果){
MainActivity.emailV.setText(结果);
}
@凌驾
受保护的字符串doInBackground(对象…参数){
JSONArray jsonparams=(JSONArray)params[1];
String methodname=params[0]。toString();
输入流为;
试一试{
DefaultHttpClient httpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(服务URI+methodname);
StringEntity se=新的StringEntity(jsonparams.toString(),“UTF-8”);
setContentType(“application/json;charset=UTF-8”);
httpPost.setEntity(se);
Log.e(“Gerhard”,jsonparams.toString());
HttpResponse HttpResponse=httpClient.execute(httpPost);
HttpEntity HttpEntity=httpResponse.getEntity();
is=httpEntity.getContent();
InputStreamReader i=新的InputStreamReader(is);
BufferedReader str=新的BufferedReader(i);
字符串msg=str.readLine();
Log.e(“Gerhard”,msg);
返回味精;
}捕获(不支持的编码异常e){
e、 printStackTrace();
}捕获(客户端协议例外e){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
返回null;
}
私有字符串转换字符串(位图图像){
ByteArrayOutputStream bos=新建ByteArrayOutputStream();
image.compress(位图.CompressFormat.JPEG,100,bos);
字节[]数据=bos.toByteArray();
String mediaString=Base64.encodeToString(数据,Base64.URL\u-SAFE);
返回媒体字符串;
}
}
我的问题包含多个部分:1.如何将图像文件和其他数据类型一起发送到RegisterUser方法并以json格式获得响应?
2.对于视频文件和图像文件是否同样有效?
3.我想从服务返回customdatatype(在本例中为ResultSet),是否需要为此执行一些特殊操作?
请不要将其标记为重复,因为我已经尝试了许多示例,但无法解决问题,也无法混淆。
请帮帮我!!!提前向您致谢。
问候,
Sourabh要向WCF发送媒体文件(或任何任意文件),您需要有一个操作,其中请求正文中唯一的参数类型为
Stream
。这意味着您可以对操作使用其他参数,但它们需要通过URI传递(使用[WebInvoke]
属性的UriTemplate
属性)-请参阅位于的帖子中的更多信息
在您的示例中,您将得到如下代码:
[OperationContract]
[WebInvoke(Method = "POST",
UriTemplate = "RegisterUser?emailId={EmailID}&name={Name}&mobile={Mobile}&IMEI={IMEI}",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
RequestFormat= WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
ResultSet RegisterUser(string EmailID, string Name,Stream profilepic, string Mobile, long IMEI);
在客户机中,您不使用JSON,而是在请求URI中传递非文件参数,并在请求正文中传递文件内容
对于你的其他问题:是的,它也适用于视频文件(对于任何任意数据而言);不,您不需要为退货类型做任何特殊的操作-它应该可以正常工作。谢谢您的回复!!!它帮助了我。我在没有图像(仅url参数)的情况下尝试了它,它正在工作。
但当我尝试在请求正文中使用图像时,它没有工作。我确信我在http post中放置图像时犯了一些错误。这是我正在使用的代码。请忽略上面的注释。谢谢你的回复!!!我在没有图像的情况下尝试了它,但当我在请求体中尝试图像时,它不起作用。这是我正在使用的代码。MultipartEntity mpEntity=新的MultipartEntity();文件文件=新文件(imagepath);ContentBody cbFile=新文件体(文件“image/jpeg”);addPart(“图像”,cbFile);httpPost.setEntity(mpEntity);请告诉我如何在http请求正文中发送图像。我从其他教程中获得了上述代码。如果你能告诉我准确的编码,而不做什么解释,那会更有帮助。感谢和问候,苏拉比你不应该使用
多协议
-而是使用ByteArrayEntity
。服务器中的流
参数将接收客户端发送的字节,您希望从文件中发送准确的字节。