【问题标题】:how to send media file to wcf rest json service and get string return response in json format如何将媒体文件发送到 wcf rest json 服务并以 json 格式获取字符串返回响应
【发布时间】:2013-06-27 17:43:40
【问题描述】:


请不要将其标记为重复,因为我已经战斗了很多天并且已经尝试了很多示例但无法解决和混淆。我是 WCF 和 android 的新手还有
所以我创建了一个 WCF 服务,其中包含一些 get 和 post 方法,如下所示

[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;
}
}

我的问题包含多个部分:
1. 如何将图像文件与其他数据类型一起发送到RegisterUser方法并获得json格式的响应?
2. 视频文件和图片文件一样吗?
3. 我想从服务中返回自定义数据类型(在本例中为 ResultSet),我需要为此做些什么特别的事情吗?

请不要将其标记为重复,因为我已经尝试了很多示例但无法解决并感到困惑。

请帮帮我!!!非常感谢。
问候,
苏拉布

【问题讨论】:

    标签: android json image wcf upload


    【解决方案1】:

    要将媒体文件(或任何任意文件,就此而言)发送到 WCF,您需要执行一个操作,其中 请求正文中的唯一参数 类型为 Stream。这意味着您可以将其他参数用于操作,但它们需要通过 URI 传递(使用 [WebInvoke] 属性的 UriTemplate 属性) - 请参阅 http://blogs.msdn.com/b/carlosfigueira/archive/2008/04/17/wcf-raw-programming-model-receiving-arbitrary-data.aspx 的帖子中的更多信息。

    在您的示例中,您将拥有类似于以下代码的内容:

    [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 帖子中时犯了一些错误。这是我正在使用的代码。
    • 请忽略以上评论。感谢您的回复!!!我在没有图像的情况下尝试了它然后它正在工作。但是当我在请求正文中尝试使用图像时它不起作用。这是我正在使用的代码。 MultipartEntity mpEntity = new MultipartEntity();文件文件 = 新文件(图像路径); ContentBody cbFile = new FileBody(file, "image/jpeg"); mpEntity.addPart("图像", cbFile); httpPost.setEntity(mpEntity); 请告诉我如何在 http 请求正文中发送图像。我从其他教程中获得了上述代码。如果你能告诉我确切的编码而几乎没有解释,那会更有帮助。谢谢和问候,Sourabh
    • 您不应该使用MultipartEntity - 请改用ByteArrayEntity。服务器中的Stream 参数将接收客户端发送的字节,而您希望从文件中发送确切的字节。
    猜你喜欢
    • 2021-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多