【问题标题】:Android post request to wcf serviceAndroid 向 wcf 服务发送请求
【发布时间】:2016-01-24 15:59:14
【问题描述】:

我正在将数据从 android 发布到 wcf 服务,但使用 HttpURLConnection 收到 Bad Request 错误。

安卓代码:

`public User RegisterPost(Context context, User rUser) throws UnsupportedEncodingException{

    String url = context.getResources().getString(R.string.SERVICE_URL)+ "Signup";
    try
    {
        JSONObject userValue =  new JSONObject();
        JSONObject user =  new JSONObject();

        userValue.put("name", rUser.name);
        userValue.put("email", rUser.email);
        userValue.put("password", rUser.password);
        userValue.put("phone",  rUser.phone);
        userValue.put("nic", rUser.nic);
        userValue.put("userType", rUser.userType);
        userValue.put("image", rUser.image);

        user.put("user", userValue.toString());

        String response = postData(url, user);

    }
    catch(Exception ex)
    {
        ex.printStackTrace();
    }
    return  null;
   }`

postData() 函数在同一个文件中。

public String postData(String urlpath, JSONObject json)
  {
    HttpURLConnection connection = null;
    try {
        URL url=new URL(urlpath);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "application/json");
        OutputStreamWriter streamWriter = new OutputStreamWriter(connection.getOutputStream());
        Log.d("write data",json.toString());
        streamWriter.write(json.toString());
        streamWriter.flush();
        StringBuilder stringBuilder = new StringBuilder();
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK){
            InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());
            BufferedReader bufferedReader = new BufferedReader(streamReader);
            String response = null;
            while ((response = bufferedReader.readLine()) != null) {
                stringBuilder.append(response + "\n");
            }
            bufferedReader.close();

            Log.d("HTTP_OK response", stringBuilder.toString());
            return stringBuilder.toString();
        } else {
            Log.e("else response", connection.getResponseMessage());
            return null;
        }
    } catch (Exception exception){
        Log.e("test", exception.toString());
        return null;
    } finally {
        if (connection != null){
            connection.disconnect();
        }
    }

}

json 数据发送到服务;

{
"user": "{\"name\":\"rrr rrr\",\"email\":\"rrr@eemail.com\",\"password\":\"123\",\"phone\":\"12333333\",\"nic\":\"44444444\",\"userType\":\"Passenger\",\"image\":\"55akasdfadphpoijpiojasdfasdfasdfasdfasdfasdfasdfasdf\"}"
}

这里是 WCF 服务代码;

 [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "/Signup",
                 RequestFormat = WebMessageFormat.Json,
                ResponseFormat = WebMessageFormat.Json)]
    bool Signup(ReturnUserData user);



public bool Signup(ReturnUserData user)
    {

        user usr = new user();
        usr.name = user.name;
        usr.email = user.email;
        usr.password = user.password;
        usr.phone = user.phone;
        usr.nic = user.nic;
        usr.userType = user.userType;
        usr.image = user.image;
        db.users.Add(usr);
        db.SaveChanges();
        return true;
    }


 public class ReturnUserData
 {

    public string id { get; set; }
    public string name { get; set; }
    public string email { get; set; }
    public string password { get; set; }
    public string phone { get; set; }

    public string userType { get; set; }

    public string image { get; set; }

}

【问题讨论】:

  • 当我使用邮递员测试这个服务时,我得到了这个错误。 The server encountered an error processing the request. The exception message is 'There was an error deserializing the object of type AlumniService.ReturnUserData. Encountered invalid character ' '.'. See server logs for more details. The exception stack trace is:

标签: c# android json wcf httpurlconnection


【解决方案1】:

我终于弄清楚了问题所在,我的RegisterPost()函数的实现有一些错误,所以我更改了函数。

public User RegisterPost(Context context, User rUser) throws UnsupportedEncodingException{

    String url = context.getResources().getString(R.string.SERVICE_URL)+ "Signup";
    try
    {
        JSONObject newUser =  new JSONObject();
        newUser.put("name", rUser.name);
        newUser.put("email", rUser.email);
        newUser.put("password", rUser.password);
        newUser.put("phone",  rUser.phone);
        newUser.put("nic", rUser.nic);
        newUser.put("userType", rUser.userType);
        newUser.put("image", rUser.image);

        String response = postData(url, newUser.toString());
        Log.d("response", response);

        if(response!="")
        {
            try {
                JSONObject user = new JSONObject(response);
                User returnUser = new User( user.getInt("id"),user.getString("name"),user.getString("email"),user.getString("password"),user.getString("phone"),user.getString("nic"),user.getString("userType"), user.getString("street"), user.getString("city"), user.getString("country"), Double.parseDouble(user.getString("lat")), Double.parseDouble(user.getString("lng")),user.getInt("is_login"),user.getInt("is_vehicle_added"), user.getString("reg_id"), user.getInt("isError"), user.getString("errorMessage"), user.getString("image"));
                return returnUser;
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

    }
    catch(Exception ex)
    {
        ex.printStackTrace();
    }
    return  null;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多