在向ASP.Net Web API中的API版本发送电子邮件和密码后尝试获取令牌时,在android studio中获取500个响应代码

时间:2018-11-20 13:51:55

标签: android-studio asp.net-web-api

这是我的android studio代码。我把所有都放在asyncTask下。我通过的网址 新的HTTPAsyncTask()。execute(“ http://192.168.225.60/IFAPI/api/user/UserDetails”)。

当我删除conn.setRequestProperty(“ Content-Type”,“ application / text; charset = utf-8”)时,我可以登录,但没有收到令牌。我检查了提琴手的API,需要输入内容类型,否则我将收到500个内部服务器错误。请帮忙。

private class HTTPAsyncTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
        // params comes from the execute() call: params[0] is the url.
        try {
            try {
                return HttpPost(urls[0]);
            } catch (JSONException e) {
                e.printStackTrace();
                return "Error!";
            }
        } catch (IOException e) {
            return "Unable to retrieve web page. URL may be invalid.";
        }
    }
    // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {
        if(result.equalsIgnoreCase("ok"))
        {
            Toast.makeText(Login_Activity.this,"Welcome!!!", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(Login_Activity.this, Home_Activity.class);
            startActivity(intent);

        }

        else
            Toast.makeText(Login_Activity.this,"Invalid Details.", Toast.LENGTH_SHORT).show();
    }
}

private String HttpPost(String myUrl) throws IOException, JSONException {

    URL url = new URL(myUrl);

    // 1. create HttpURLConnection
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/text; charset=utf-8");

    // 2. build JSON object
    JSONObject jsonObject = buidJsonObject();

    // 3. add JSON content to POST request body
    // 4. make POST request to the given URL
   setPostRequestContent(conn, jsonObject);
    int response = conn.getResponseCode();

    InputStreamReader inputStreamReader = new InputStreamReader(conn.getInputStream());
    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
    StringBuilder stringBuilder = new StringBuilder();
    String bufferedStrChunk = null;

    while((bufferedStrChunk = bufferedReader.readLine()) != null){
        stringBuilder.append(bufferedStrChunk);
    }

    String responseMessage = conn.getResponseMessage();
    if(responseMessage.equalsIgnoreCase("OK"))
    {
        db = new UserLoginTokenDb(this);
        String token = db.getToken();
        if(token == null)
            db.addToken(stringBuilder.toString()); //saving token in local database

        // set
        Globals g = Globals.getInstance();
        g.setData(db.getToken());
    }

    conn.disconnect();
    // 5. return response message
    return conn.getResponseMessage();

}

private JSONObject buidJsonObject() throws JSONException {

    JSONObject jsonObject = new JSONObject();
    db = new UserLoginTokenDb(this);
    String token = db.getToken();
    jsonObject.accumulate("Token",  token == null ? "" : token);
    jsonObject.accumulate("Email",  txtEmail.getText().toString());
    jsonObject.accumulate("Password",  txtPassword.getText().toString());

    return jsonObject;
}

private void setPostRequestContent(HttpURLConnection conn,
                                   JSONObject jsonObject) throws IOException {

    OutputStream os = conn.getOutputStream();
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
    writer.write(jsonObject.toString());
    Log.i(Registration_Activity.class.toString(), jsonObject.toString());
    writer.flush();
    writer.close();
    os.close();
}

Web API代码:

[HttpPost]
    public HttpResponseMessage UserLogin(JObject jsonResult)
    {
        if(jsonResult == null)
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No such user exist");

        Dictionary<String, String> list = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonResult.ToString());

        String[] st = new String[3];
        int i = 0;

        foreach (KeyValuePair<String, String> s in list)
        {
            st[i] = s.Value;
            i++;
        }
        String token = st[0];
        String email = st[1];
        String password = st[2] ;

        try
        {
            using (IFDbEntities entities = new IFDbEntities())
            {

                User user = entities.Users.FirstOrDefault(j => j.login_token == token);
                if (user != null)
                {
                    return Request.CreateResponse(HttpStatusCode.OK, user.login_token);
                }
                else
                {
                    User existingUser = entities.Users.FirstOrDefault(k => k.Email == email && k.Password == password);
                    if (existingUser != null)
                    {
                        return Request.CreateResponse(HttpStatusCode.OK, existingUser.login_token);
                    }
                    else
                    {
                        return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No such user exist");
                    }

                }
            }
        }

        catch (Exception ex)
        {
            return Request.CreateErrorResponse(HttpStatusCode.BadGateway, ex);
        }
    }

0 个答案:

没有答案