【问题标题】:RESTful Web service json responses return null in javaRESTful Web 服务 json 响应在 java 中返回 null
【发布时间】:2016-08-16 10:29:52
【问题描述】:

我是使用 Java 进行 Android 和 Web 服务编程的新手,我在将我的 Android 应用程序连接到我的 Java Web 服务时遇到了问题。 我已经在 tomcat 上部署了 Web 服务,它正在我的手机浏览器上进行连接,但是每次我尝试从我的 Android 应用程序连接时,HttpClient 都会返回 null。

这是我的源代码。

public class ServiceHandler {

static String response = null;
public final static int GET = 1;
public final static int POST = 2;

public ServiceHandler() {

}

/**
 * Making service call
 * @url - url to make request
 * @method - http request method
 * */
public String makeServiceCall(String url, int method) {
    return this.makeServiceCall(url, method, null);
}

/**
 * Making service call
 * @url - url to make request
 * @method - http request method
 * @params - http request params
 * */
public String makeServiceCall(String url, int method, List<NameValuePair> params) {
    try {
        // http client
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpEntity httpEntity = null;
        HttpResponse httpResponse = null;

        // Checking http request method type
        if (method == POST) {
            HttpPost httpPost = new HttpPost(url);
            // adding post params
            if (params != null) {
                httpPost.setEntity(new UrlEncodedFormEntity(params));
            }

            httpResponse = httpClient.execute(httpPost);

        } else if (method == GET) {
            // appending params to url
            if (params != null) {
                String paramString = URLEncodedUtils
                        .format(params, "utf-8");
                url += "?" + paramString;
            }
            HttpGet httpGet = new HttpGet(url);

            httpResponse = httpClient.execute(httpGet);

        }
        httpEntity = httpResponse.getEntity();
        response = EntityUtils.toString(httpEntity);

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return response;

}

}

private class Authenticate extends AsyncTask<Void, Void, Void>{

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(LoginActivity.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();
    }

    @Override
    protected Void doInBackground(Void... arg0) {
        // Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();


        String url = "http://192.168.34.1:8080/SchoolWebService/rest/User/"+username+","+password;

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

        Log.d("Response: ", "> " + jsonStr);

        if (jsonStr != null) {
            try {
                JSONObject c = new JSONObject(jsonStr);

                String uname = c.getString("username");
                String pword = c.getString("password");
                snackbar.setText("Authenticated").show();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            snackbar.setText("Authentication Failed!").show();
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();
    }
}

Log.d(....);语句总是返回 null。

【问题讨论】:

  • 除了使用AsyncTask使用Volley解析json数据...
  • 我不知道该怎么做
  • 我的代码做错了什么?
  • 您可能会在 makeServiceCall 中遇到异常,然后捕获该异常并且方法返回 null。 e.printStackTrace 是否有任何输出?另请参阅此问题:stackoverflow.com/questions/3855187/…
  • 不。没看到

标签: java android json


【解决方案1】:

您的服务器日志说什么?请求甚至到达服务器吗?服务器计算机上的 Tcpdump 或 Wireshark 跟踪将帮助您了解浏览器请求和 Android 请求的不同之处。

我已经有一段时间没有直接使用 HttpClinet 了。您应该考虑为您的 http 请求使用库。这是一个使用 Volley 的示例,正​​如另一位用户所建议的那样。

    String username = "george";
    String password = "jetson";
    String url = "http://192.168.34.1:8080/SchoolWebService/rest/User/"+username+","+password;

    Context appContext = InstrumentationRegistry.getTargetContext();
    RequestQueue queue = Volley.newRequestQueue(appContext);

    StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
          new Response.Listener<String>() {
              @Override
              public void onResponse(String response) {

                  Log.d("TAG", "success: " + response);

              }
          }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });

    queue.add(stringRequest);

考虑使用摘要验证,网址中的明文密码不是一个很好的解决方案,即使它是一个学校项目。

【讨论】:

    【解决方案2】:

    谢谢大家,但我终于找到了解决方案。正如@foobar 评论的那样, makeServiceCall 方法抛出了一个我没有看到的异常,所以我取出 printStackTrace() 并将其替换为 Log.e(TAG, Log.getStackTraceString(e));然后我发现我的手机无法通过网络连接到我的电脑。我收到连接被拒绝的错误消息。所以我做了以下事情。

    1. 在我的手机上打开了 USB 网络共享。
    2. 从命令提示符键入 ipconfig 并从我的 USB 连接 192.168.42.xxx 获取我的 IPv4 地址。
    3. 我用这个替换了我的 URL 中的 IP 地址。
    4. 我在端口号上的防火墙中添加了入站和出站规则,一切都开始工作了

    谢谢大家

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-11
      • 2012-01-09
      • 1970-01-01
      • 2014-01-12
      • 2011-05-30
      • 2014-11-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多