【问题标题】:Sending json to webservice, receiving null. - Android将 json 发送到 web 服务,接收 null。 - 安卓
【发布时间】:2012-11-29 00:12:53
【问题描述】:

我是新手。从服务器读取 json 的 Web 服务有效,但是当我在 Android 中通过 json 创建新记录时,它会发送,但我收到 null。

代码

HttpPost post = new HttpPost("http://192.168.42.194/app/web/app.php/android/buscar");
post.setHeader("content-type", "application/json;charset=UTF-8");
try {
    JSONStringer dato = new JSONStringer().object().key("cadena").value("valor").endObject();
    StringEntity entidad = new StringEntity(dato.toString());
    post.setEntity(entidad);
    HttpClient cliente = new DefaultHttpClient();
    HttpResponse respuesta = cliente.execute(post);
    String obtiene = EntityUtils.toString(respuesta.getEntity());
    JSONObject object2 = new JSONObject(obtiene);
    String mensaje = object2.getString("cod");
    Log.e("LOG", mensaje.toString());
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
    alertDialogBuilder.setTitle("Your Title");
    alertDialogBuilder.setMessage("Enviado "+ mensaje);
    AlertDialog alertDialog = alertDialogBuilder.create();
    alertDialog.show();
} catch (Exception ex) {
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
    alertDialogBuilder.setTitle("Error");
    alertDialogBuilder.setMessage("Enviar " + query.getText());
    AlertDialog alertDialog = alertDialogBuilder.create();
    alertDialog.show();
}

【问题讨论】:

  • 手动将帖子发布到端点时会发生什么?它有效吗?预期的反应是什么?
  • 这个 HttpResponse respuesta = cliente.execute(post);返回代码 200,不是 null,而是这一行: String obtiene = EntityUtils.toString(respuesta.getEntity());return 服务器的 null,我使用 restclient-ui-3.1 来尝试请求和工作,我可以从服务器读取 json ,但我无法将 json 发送到服务器
  • 我想了解的是客户端服务器是否有问题。当您使用 restclient 使用 JSON 手动构建帖子并将其 POST 到服务器时,它是否有效?
  • 有效,错误在android代码中

标签: android json web-services


【解决方案1】:

尝试在 StringEntity 上设置标题而不是帖子本身,JSON 默认为 UTF-8,因此不需要

HttpClient cliente = new DefaultHttpClient();
JSONObject dato = new JSONObject();
try {
    HttpPost post = new HttpPost("http://192.168.42.194/app/web/app.php/android/buscar");
    dato.put("cadena", "valor");
    StringEntity entidad = new StringEntity(dato.toString());  
    entidad.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
    post.setEntity(entidad);
    HttpResponse respuesta = cliente.execute(post);
} catch (Exception ex) {
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
    alertDialogBuilder.setTitle("Error");
    alertDialogBuilder.setMessage("Enviar " + query.getText());
    AlertDialog alertDialog = alertDialogBuilder.create();
    alertDialog.show();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-05
    • 2014-07-25
    • 1970-01-01
    相关资源
    最近更新 更多