0

我有一个安卓应用程序。我必须通过带有两个参数的 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();
    }
}
}

用邮递员编辑 在此处输入图像描述

4

3 回答 3

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)

我希望它对你有用......

于 2014-02-04T05:03:27.717 回答
0

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

在这里,我找到了 Android 中的 HttpGet 请求示例。

并且还在这里找到了 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;
}

很抱歉迟到找到解决方案。

于 2014-02-04T05:06:14.493 回答
0

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

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

在此处输入图像描述

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

于 2014-02-04T04:30:52.027 回答