【问题标题】:Android httppost authentication error with 401 response code带有 401 响应代码的 Android httppost 身份验证错误
【发布时间】:2014-02-04 04:12:13
【问题描述】:

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

这是我的日志文件:

这是我的活动:

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();
    }
}
}

用邮递员编辑

【问题讨论】:

  • 你试过调试了吗?
  • 您在服务器上有任何身份验证吗?
  • 你能发布一些服务器端的代码吗?
  • @PratikButani,实际上服务器端不是由我维护的。所以没有办法获取服务器端的代码。您在谈论哪种服务器上的身份验证?
  • 一些 Authentication 参数传入 Header 信息,可能你在那里丢失了。

标签: android http-post androidhttpclient


【解决方案1】:
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】:

    我建议您使用 cURL 测试您的 REST api (url) 或使用任何 google crome 应用程序(如 POSTMAN google chrome 扩展程序)来快速设置,它可以帮助您以最简单的方式测试 REST api!

    如果你的rest api工作正常,那么考虑使用你的代码,逐步尝试跟踪服务器实现是否错误或客户端实现错误或url、参数错误!还要检查您的AndroidManifest.xml 中的&lt;uses-permission android:name="android.permission.INTERNET" /&gt;

    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 客户端的代码并且更高效

    【讨论】:

    • 不错的建议。它很有帮助。
    • 那里一切正常。那么我的代码有什么问题??????我用邮递员得到了正确的结果。我使用了互联网许可。
    • @MohammadRajob 我已经发布了我的答案。看看可能会对你有所帮助。
    • @MohammadRajob 先试试 https 吧!还问你的服务器开发人员,他用带有证书的 POST 方法制作了 SSL?
    • @MohammadRajob 可能是您的服务器开发人员获取 JSON 格式的数据。你有我的答案吗?
    【解决方案3】:

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

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

    还有 Here 找到了 StackOverflow 解决方案。

    已编辑:

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

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

       @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;
    }
    

    抱歉迟到了。

    【讨论】:

    • 那里不接受缓冲区读取器。 bufferreader 下的 rel 行。
    • 现在检查一下,这只是常识问题,您必须删除自己。
    猜你喜欢
    • 2012-07-30
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 2018-10-09
    • 1970-01-01
    • 1970-01-01
    • 2012-08-06
    • 1970-01-01
    相关资源
    最近更新 更多