2016-12-02 34 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

相关问题