0

私はアンドロイドアプリケーションを持っています。2 つのパラメーターを使用して、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

cURLを使用して REST API (URL) をテストすることをお勧めします。または、REST API を最も簡単な方法でテストするのに役立つPOSTMAN Google Chrome 拡張機能 などの Google Chrome アプリを使用してすばやくセットアップすることをお勧めします。

残りの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));

ソース:そう

非同期タスクの使用にうんざりしている場合は、ボレーを使用して http クライアントのコードを最小化し、より効率的です

于 2014-02-04T04:30:52.027 に答える
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 に答える