簡體   English   中英

httpResponse在Java中返回null

[英]httpResponse returns null in java

我正在嘗試從服務器端獲得對應用程序的響應,並且HTTP響應中為null 將URL粘貼到瀏覽器中時,得到所需的響應。

網址:“ http:// localhost:8080 / TBookServerSide / LoginServlet?u = admin&p = 123

響應:

{ "info" : "success" }

就像我在info參數中返回帶有成功字樣的JSON對象一樣,但是當我嘗試通過Android應用程序時,卻得到了null

我需要填寫登錄表單(用戶名和密碼),然后按登錄按鈕使其正常工作。

這是我的代碼:

LoginFragment.java:

public class LoginFragment extends Fragment {
    public LoginFragment() {
        // Required empty public constructor
    }

    EditText firstNameText;
    EditText lastNameText;
    EditText userNameText;
    EditText passwordText;
    EditText emailText;

    Button loginButton;
    Button signUpPageButton;

    // Creating JSON Parser object
    com.example.liran.tbookandroid.LoginPage.JSONParser jParser = new com.example.liran.tbookandroid.LoginPage.JSONParser();


    private static String url_login = "http://localhost:8080/TBookServerSide/LoginServlet";
    //JSONArray incoming_msg = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_login, container, false);

        (...)

        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                User newUser = new User();
                String userName = userNameText.getText().toString();
                String password = passwordText.getText().toString();

                newUser.setUserName(userName);
                newUser.setPassword(password);

                Log.d("Press Button:","Login Button has been pressed");
                new LoginWithServlet(newUser).execute();
            }
        });

        return root;
    }

    private class LoginWithServlet extends AsyncTask<String, String, String> {
        JSONObject json;
        User user;
        boolean isUserExist = false;

        public LoginWithServlet(User user) {
            this.user = user;
        }

        @Override
        protected String doInBackground(String... params2) {
            // Getting username and password from user input
            String username = user.getUserName();
            String pass = user.getPassword();

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("u", username));
            params.add(new BasicNameValuePair("p", pass));
            json = jParser.makeHttpRequest(url_login, "GET", params);
            String s = null;

            try {
                if (json != null) {
                    s = json.getString("info");
                    Log.d("Msg", json.getString("info"));
                    if (s.equals("success")) {
                        // SUCCEED LOGIN !!!!
                        Log.d("Login Servlet: "," Login Succeed");
                        ((MainActivity) getActivity()).openMainPageFragment();
                        ((MainActivity) getActivity()).showBarButtons();
                    } else {
                        // FAILED LOGIN
                        Log.d("Login Servlet: "," Login failed");
                    }
                } else {
                    Log.e("JSon:"," is NULL");
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        }
    }

}

JSONParser.java

public class JSONParser {
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    static InputStream iStream = null;
    static JSONArray jarray = null;
    //static String json = "";

    // constructor
    public JSONParser() {}

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) {
        // Making HTTP request
        try {
            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            } else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }

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

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

LogCat:

com.example.liran.tbookandroid E/Buffer Error: Error converting result java.lang.NullPointerException: lock == null
com.example.liran.tbookandroid E/JSON Parser: Error parsing data org.json.JSONException: End of input at character 0 of 
com.example.liran.tbookandroid E/JSon::  is NULL

我不知道為什么它不能按預期工作,非常感謝您的幫助。

http://localhost:8080/僅由您的計算機標識,因為它托管在該計算機上。 在這里, localhost是指您在其中配置服務器的計算機,因此您的瀏覽器可以找到/查找它。

當您在移動設備上調用同一個設備時, localhost表示您的移動設備不是計算機。 這就是為什么它不起作用。

您仍然可以使用本地服務器進行開發。 嘗試連接像這樣

如果您正在運行Windows,請找到計算機的IP:按Windows鍵+ R,然后鍵入CMD,然后鍵入ipconfig,然后按Enter鍵

之后,您可以在IPv4-Address前面看到您的IP地址

輸入它而不是localhost

您知道本地主機的含義嗎?它是您的個人計算機的本地ip,因此您可以在瀏覽器中成功完成。

如果您只想在應用程序中進行測試,則應在PC上打開一個熱點,然后在其上連接Android手機。

或將您的本地網址更改為如下所示的外部網址: http ://wthrcdn.etouch.cn/weather_mini?citykey =101010100

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM