Android响应代码的Android httppost身份验证错误

时间:2014-02-04 04:12:13

标签: android http-post androidhttpclient

我有一个Android应用程序。我必须通过带有两个参数的httppost从服务器获取数据。但我每次都得到响应代码401。它应该是200。

这是我的日志文件:

  

enter image description here

这是我的活动:

public class LoginActivity extends Activity implements OnClickListener {

Button login;
EditText user, pass;
CheckBox ck;
String FILENAME = "check";
String checkenords;

String FILETOKEN = "token";
String tokenStr;

String FILEEmail = "email";
String emailStr;

String responseStr;
String usernamefromuser;
int responsecode;
String passfromuser;
ProgressDialog pDialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.sign_in);
    user = (EditText) findViewById(R.id.editText1);
    pass = (EditText) findViewById(R.id.editText2);
    ck = (CheckBox) findViewById(R.id.checkBox1);
    login = (Button) findViewById(R.id.btnlogin);

    login.setOnClickListener(this);
}


@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    new GetContacts().execute();
}

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

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(LoginActivity.this);
        pDialog.setMessage("Wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected Void doInBackground(Void... arg0) {
        // Creating service handler class instance
        usernamefromuser = user.getText().toString();
        passfromuser = pass.getText().toString();

        Log.e("successss", "888888888888");
        Log.e("Username", "User:" + usernamefromuser);
        Log.e("Password", "pass:" + passfromuser);
        HttpClient client = new DefaultHttpClient();
        String url = "http://54.228.199.162/api/auth";
        HttpPost httppost = new HttpPost(url);
        // httppost.setHeader("Content-type", "application/json");
        // httppost.setHeader("Accept", "application/json");

        try {
            List<NameValuePair> namevalpair = new ArrayList<NameValuePair>();
            namevalpair.add(new BasicNameValuePair("pass", passfromuser));
            namevalpair.add(new BasicNameValuePair("email",
                    usernamefromuser));
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(
                    namevalpair, HTTP.UTF_8);
            httppost.setEntity(entity);
            HttpResponse httpresponse = client.execute(httppost);
            responsecode = httpresponse.getStatusLine().getStatusCode();
            responseStr = EntityUtils.toString(httpresponse.getEntity());
            Log.d("Authentication", "" + responsecode);
            // Log.d("httpresponseeeee", httpresponse.toString());
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        ;

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (responsecode == 200) {
            tokenStr = responseStr;
            emailStr = usernamefromuser;
            try {
                FileOutputStream fos = openFileOutput(FILETOKEN,
                        Context.MODE_PRIVATE);
                fos.write(tokenStr.getBytes());
                fos.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            try {
                FileOutputStream fos = openFileOutput(FILEEmail,
                        Context.MODE_PRIVATE);
                fos.write(emailStr.getBytes());
                fos.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


            if (ck.isChecked()) {
                checkenords = "enable";
                try {
                    FileOutputStream fos = openFileOutput(FILENAME,
                            Context.MODE_PRIVATE);
                    fos.write(checkenords.getBytes());
                    fos.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                Intent inteGps = new Intent(LoginActivity.this, Gps.class);
                startActivity(inteGps);
                finish();
            } else {
                Intent inteGps = new Intent(LoginActivity.this, Gps.class);
                startActivity(inteGps);
                finish();
            }
        } else if (responsecode == 401) {

            Toast.makeText(getApplicationContext(), getApplicationContext().getResources().getString(R.string.userwrong),
                    Toast.LENGTH_LONG).show();

        } else{
            Toast.makeText(getApplicationContext(), getApplicationContext().getResources().getString(R.string.tryagain), Toast.LENGTH_LONG).show();
        }
        pDialog.dismiss();
    }
}
}

以POSTMAN编辑 enter image description here

3 个答案:

答案 0 :(得分:0)

我建议您使用cURL测试您的REST api(网址)或快速设置使用任何谷歌crome应用程序,如POSTMAN谷歌浏览器扩展程序,它可以帮助您以最简单的方式测试REST api !

如果你的api工作正常,那么考虑使用你的代码,一步一步尝试跟踪服务器实现是否错误或客户端实现错误或url,参数错误!还要检查<uses-permission android:name="android.permission.INTERNET" />

中的AndroidManifest.xml

enter image description here

public String userSignIn(String user, String pass, String authType)
            throws Exception {



        DefaultHttpClient httpClient = new DefaultHttpClient();
        String url = "https://example/authenticate";


        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();


        nameValuePairs.add(new BasicNameValuePair("userName", user));
        nameValuePairs.add(new BasicNameValuePair("password", pass));
        // Add more parameters as necessary

        // Create the HTTP request
        HttpParams httpParameters = new BasicHttpParams();

        // Setup timeouts
        HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
        HttpConnectionParams.setSoTimeout(httpParameters, 15000);

        HttpClient httpclient = new DefaultHttpClient(httpParameters);
        HttpPost httppost = new HttpPost(
                url);
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
    String responseString = EntityUtils.toString(response.getEntity());
            Log.d("resp test", responseString);
    }

编辑:

尝试

DefaultHttpClient client = new DefaultHttpClient();
client.getCredentialsProvider().setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials(username, password));

来源:SO

如果您厌倦了使用异步任务,volley可以最大限度地减少http客户端的代码,并且效率更高

答案 1 :(得分:0)

Use bellow line in your code.....



HttpParams httpParams = new BasicHttpParams();

HttpClient httpClient = new DefaultHttpClient(httpParams);

HttpPost requestPost = new HttpPost(url);

requestPost.setHeader("*_*****_USERNAME", "admin******");

requestPost.setHeader("*_*****_PASSWORD", "admin@*****");

requestPost.setHeader("Content-Type","application/x-www-form-urlencoded");
//(as per your requirement)

我希望它能为你工作.....

答案 2 :(得分:0)

根据您编辑的问题,我认为您必须使用 HttpGet 在服务器上发送身份验证。

Here我在Android中找到了HttpGet请求的示例。

并且 Here 找到了StackOverflow解决方案。

编辑:

我检查了您的POSTMAN,发现您的服务器正在接受JSON数据。 你可以在Image中看到:

enter image description here

所以现在你必须尝试这段代码:

   @Override
    protected Void doInBackground(Void... arg0) {

    // Creating service handler class instance
    usernamefromuser = user.getText().toString();
    passfromuser = pass.getText().toString();

    InputStream inputStream = null;
    String result = "";
    try {

        // 1. create HttpClient
        HttpClient httpclient = new DefaultHttpClient();

        // 2. make POST request to the given URL
        HttpPost httpPost = new HttpPost(url);

        String json = "";

        // 3. build jsonObject
        JSONObject jsonObject = new JSONObject();
        jsonObject.accumulate("email", usernamefromuser);
        jsonObject.accumulate("pass", passfromuser);

        // 4. convert JSONObject to JSON to String
        json = jsonObject.toString();

        // ** Alternative way to convert Person object to JSON string usin Jackson Lib 
        // ObjectMapper mapper = new ObjectMapper();
        // json = mapper.writeValueAsString(person); 

        // 5. set json to StringEntity
        StringEntity se = new StringEntity(json);

        // 6. set httpPost Entity
        httpPost.setEntity(se);

        // 7. Set some headers to inform server about the type of the content   
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");

        // 8. Execute POST request to the given URL
        HttpResponse httpResponse = httpclient.execute(httpPost);

        responsecode = httpresponse.getStatusLine().getStatusCode();
        responseStr = EntityUtils.toString(httpresponse.getEntity());

    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }

    return null;
}

很抱歉迟到了解决方案。