2016-12-02 119 views
0

我正嘗試使用以下憑證創建用戶登錄bu。我從服務器得到了一個url,但無法使用post方法,請給我一些代碼片段給我。如何使用post方法登錄並傳遞參數android

在此先感謝。

傳遞參數: 「USER_NAME」: 「8013977」, 「user_pass」: 「8013977」

我的代碼片段:

public class LoginActivity extends AppCompatActivity implements View.OnClickListener{ 

public static final String LOGIN_URL = "http://xxxxxxxx:8080/hanwha/player/login.on"; 

public static final String KEY_USERNAME="user_name"; 
public static final String KEY_PASSWORD="user_pass"; 

private EditText editTextUsername; 
private EditText editTextPassword; 
private Button buttonLogin; 

private String username; 
private String password ; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_login); 

    editTextUsername = (EditText) findViewById(R.id.editTextUsername); 
    editTextPassword = (EditText) findViewById(R.id.editTextPassword); 

    buttonLogin = (Button) findViewById(R.id.buttonLogin); 

    buttonLogin.setOnClickListener(this); 
} 


private void userLogin() { 

    username = editTextUsername.getText().toString(); 

    Log.e(KEY_USERNAME , username); 

    password ="8013977"; 
    Log.e(KEY_PASSWORD , password); 

    StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL, 
      new Response.Listener<String>() { 
       @Override 
       public void onResponse(String response) { 
        Log.e("eee", "response: " + response); 
       } 
      }, 
      new Response.ErrorListener() { 
       @Override 
       public void onErrorResponse(VolleyError error) { 
        Toast.makeText(LoginActivity.this,error.toString(),Toast.LENGTH_LONG).show(); 
       } 
      }){ 
     @Override 
     protected Map<String, String> getParams() throws AuthFailureError { 
      Map<String,String> params = new HashMap<String,String>(); 
      params.put("user_name","8013977"); 
      params.put("user_pass","8013977"); 
      return params ; 
     } 
    }; 

    RequestQueue requestQueue = Volley.newRequestQueue(this); 
    requestQueue.add(stringRequest); 
} 

private void openProfile(){ 
    Intent intent = new Intent(this, ActivityUserProfile.class); 
    intent.putExtra(KEY_USERNAME, username); 
    startActivity(intent); 
} 

@Override 
public void onClick(View v) { 
    userLogin(); 
} 

}

+0

當您嘗試運行此代碼時是否收到錯誤消息? – cokceken

+0

是在postdata字符串我用targetographer那裏得到error.In.In的那,如何使用我的憑據作爲參數 – Mounika

+0

@Mounika爲什麼你不使用排球庫 –

回答

2

你可以試試這個代碼

BasicNameValuePair _id = new BasicNameValuePair(
      "id", id); 

    List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>(); 
    nameValuePairList.add(_id); 
    JSONObject jobj = JSONfunctions.getPostUrl(yourUrl, nameValuePairList); 

public static JSONObject getPostUrl(String url, 
     List<NameValuePair> nameValuePairList) { 
    JSONObject jObject = null; 
    HttpClient httpClient = new DefaultHttpClient(); 


    // HttpPost argument 
    HttpPost httpPost = new HttpPost(url); 

    try { 
     . 
     UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(
       nameValuePairList); 


     httpPost.setEntity(urlEncodedFormEntity); 

     try { 

      HttpResponse httpResponse = httpClient.execute(httpPost); 


      InputStream inputStream = httpResponse.getEntity().getContent(); 

      InputStreamReader inputStreamReader = new InputStreamReader(
        inputStream); 

      BufferedReader bufferedReader = new BufferedReader(
        inputStreamReader); 

      StringBuilder stringBuilder = new StringBuilder(); 

      String bufferedStrChunk = null; 

      while ((bufferedStrChunk = bufferedReader.readLine()) != null) { 
       stringBuilder.append(bufferedStrChunk); 
      } 
      try { 
       jObject = new JSONObject(stringBuilder.toString()); 
      } catch (Exception e) { 
       // TODO: handle exception 
      } 

     } catch (ClientProtocolException cpe) { 

      cpe.printStackTrace(); 
     } catch (IOException ioe) { 

      ioe.printStackTrace(); 
     } 

    } catch (UnsupportedEncodingException uee) { 
     // System.out 
     // .println("An Exception given because of UrlEncodedFormEntity argument :" 
     // + uee); 
     // uee.printStackTrace(); 
    } 
    return jObject; 
} 
+0

httppost已棄用,所以我沒有獲得 – Mounika

+0

你可以嘗試URL url = new URL(「http://www.android.com/」); HttpURLConnection urlConnection =(HttpURLConnection)url.openConnection(); 嘗試InputStream in = new BufferedInputStream(urlConnection.getInputStream()); readStream(in); } finally { urlConnection.disconnect(); } – Vadivel

+0

是多數民衆贊成在我發佈,但如何通過在我的代碼片段中的參數,請給我一些建議 – Mounika

0

我用這個登錄功能,用POST;實現凌空

private void login() { 
     loading = ProgressDialog.show(context, null, "Authenticating.Please wait...",true,true); 
     StringRequest strReq = new StringRequest(Request.Method.POST, 
       "your login url", new Response.Listener<String>() { 

      @Override 
      public void onResponse(String response) { 
       Log.e(TAG, "response: " + response); 

       try { 
        JSONObject obj = new JSONObject(response); 

        // check for error flag 
        if (obj.getString("error").equals("false")) { 
         // user successfully logged in 
         loading.dismiss(); 
         JSONObject userObj = obj.getJSONObject("user"); 
         String id=userObj.getString("requestor_id"); 
         String nam= userObj.getString("name"); 
         String ema=userObj.getString("email"); 
         User user = new User(id,nam,ema); 
         // storing user in shared preferences 
         MyApplication.getInstance().getPrefManager().storeUser(user); 
         if(myPreferenceManager.isFirstLaunch()){ 
          reRegisterGCM(nam,ema); 
          myPreferenceManager.setIsFirstLaunch(false); 
         } 
         startActivity(new Intent(getApplicationContext(), MapsActivity.class)); 
         finish(); 

        } else { 
         // login error - simply toast the message 
         loading.dismiss(); 
         Toast.makeText(getApplicationContext(), "" + obj.getJSONObject("error").getString("message"), Toast.LENGTH_LONG).show(); 
        } 

       } catch (JSONException e) { 
        Log.e(TAG, "json parsing error: " + e.getMessage()); 
        Toast.makeText(getApplicationContext(), "Json parse error: " + e.getMessage(), Toast.LENGTH_SHORT).show(); 
       } 
      } 
     }, new Response.ErrorListener() { 

      @Override 
      public void onErrorResponse(VolleyError error) { 
       NetworkResponse networkResponse = error.networkResponse; 
       loading.dismiss(); 
       Log.e(TAG, "Volley error: " + error.getMessage() + ", code: " + networkResponse+" and "+error.getMessage()); 
       Toast.makeText(getApplicationContext(), "Volley error: " + error.getMessage(), Toast.LENGTH_SHORT).show(); 
      } 
     }) { 

      @Override 

      public Map<String, String> getParams() throws AuthFailureError { 
       Map<String, String> params = new HashMap<>(); 
       params.put("user_name","8013977"); 
       params.put("user_pass","8013977"); 

       Log.e(TAG, "params: " + params.toString()); 
       return params; 
      } 
      @Override 
      public Map<String, String> getHeaders() throws AuthFailureError { 
       Map<String,String> params = new HashMap<String, String>(); 
       params.put("Content-Type","application/x-www-form-urlencoded"); 
       return params; 
      } 
     }; 
     //Adding request to request queue 
     MyApplication.getInstance().addToRequestQueue(strReq); 
    } 
+0

我使用凌空,但我得到錯誤的迴應,請告訴我現在該怎麼辦 – Mounika

+0

迴應:{「result_code」:「 US02E500「,」result_msg「:」意外字符('u'(代碼117)):預計在[Source中有效值(數字,字符串,數組,對象,'true','false'或'null')\ n :[email protected]; line:1,column:2]「} – Mounika

+0

@Mounika在你的凌空中添加此方法,如圖所示我的代碼 – Mushirih

0

我還是建議你使用排庫但正如你說,這是非常緊迫的,你可以使用名稱值對張貼的參數。 您可以使用下面的代碼:

HttpPost httppost; 
StringBuffer buffer; 
HttpResponse httpResponse; 
HttpClient httpclient; 
List<NameValuePair> nameValuePairs; 

class task extends AsyncTask<String, String, Void>{ 

     @Override 
      protected void onPreExecute() { 
       super.onPreExecute(); 
       // show progress dialog 
      } 

     @Override 
     protected Void doInBackground(String... params) { 

      try { 
       httpclient = new DefaultHttpClient(); 
       ResponseHandler<String> responseHandler = new BasicResponseHandler(); 
       httppost = new HttpPost("http://yourUrl"); 
       nameValuePairs = new ArrayList<NameValuePair>(2); 
       nameValuePairs.add(new BasicNameValuePair("user_name", "8013977")); 
       nameValuePairs.add(new BasicNameValuePair("user_pass":"8013977")); 
       httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
       res = httpclient.execute(httppost,responseHandler); 
       Log.e("Response",res); 

      } catch (Exception e) { 
        e.printStackTrace(); 
       } 
      return null; 
     } 

     @Override 
     protected void onPostExecute(Void result) { 
      super.onPostExecute(result); 
        // update UI 
      } 
    } 
+0

我使用過相同的代碼,但http post被棄用,所以顯示爲空 – Mounika

+0

@Mounika然後你必須使用齊射,根據我的知識,沒有其他的選擇。 –

+0

請檢查我編輯的文章 – Mounika