java NameValuePair、HttpParams、HttpConnection 参数在登录应用程序的服务器请求类上已弃用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30740359/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NameValuePair, HttpParams, HttpConnection Params deprecated on server request class for login app
提问by DarthVader
First time asking a question here, and new to android programming. I'm following an online youtube tutorial to create a login by user "Tonikami TV". Everything is fine with the app except when it comes to the serverRequests class. I get that NameValuePair
, HttpParams
, etc. are deprecated which I understand to be outdated and unsupported since API 22. I've searched for some fixed or alternatives but can't really make sense of them and how I would apply them to my code. Any help would be greatly appreciated. Thanks :)
第一次在这里提问,也是安卓编程的新手。我正在按照在线 youtube 教程创建用户“Tonikami TV”的登录信息。除了 serverRequests 类之外,该应用程序一切正常。我得到的NameValuePair
,HttpParams
等被淘汰,我的理解是过时的和不支持的,因为API 22.我搜索了一些固定的或替代方案,但不能真正使他们的感觉和我将如何把它们应用到我的代码。任何帮助将不胜感激。谢谢 :)
@Override
protected Void doInBackground(Void... params) {
ArrayList<NameValuePair> dataToSend = new ArrayList<>();
dataToSend.add(new BasicNameValuePair("firstname", user.FirstName));
dataToSend.add(new BasicNameValuePair("lastname", user.LastName));
dataToSend.add(new BasicNameValuePair("age", user.Age + ""));
dataToSend.add(new BasicNameValuePair("emailaddress", user.EmailAddress));
dataToSend.add(new BasicNameValuePair("password", user.Password));
//possible alternative code found on stack overflow don't know exactly what to do from here.
ContentValues values= new ContentValues();
values.put("firstname", user.FirstName);
values.put("lastname", user.LastName);
values.put("age", user.Age + "");
values.put("emailaddress",user.EmailAddress);
values.put("password",user.Password);
//
HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpClient post = new HttpPost(SERVER_ADDRESS + "Register.php");
try{
post.setEntity(new URLEncoderFormEntity(dataToSend));
client.execute(post);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
Here is the entire code in the ServerRequests class. Apologies if its rather long.
这是 ServerRequests 类中的完整代码。抱歉,如果它相当长。
public class ServerRequests {
ProgressDialog progressDialog;
public static final int CONNECTION_TIMEOUT = 1000 * 15;
public static final String SERVER_ADDRESS = "http://lok8.hostingsiteforfree.com";
public ServerRequests(Context context){
progressDialog = new ProgressDialog(context);
progressDialog.setCancelable(false);
progressDialog.setTitle("Processing");
progressDialog.setMessage("Please Wait...");
}
public void storeUserDataInBackground(User user, GetUserCallback userCallback){
progressDialog.show();
new StoreUserDataAsyncTask(user,userCallback).execute();
}
public void fetchUserDataInBackground(User user, GetUserCallback callback) {
progressDialog.show();
new fetchUserDataAsyncTask(user, callback).execute();
}
public class StoreUserDataAsyncTask extends AsyncTask<Void, Void, Void>{
User user;
GetUserCallback userCallback;
public StoreUserDataAsyncTask(User user, GetUserCallback userCallback){
this.user = user;
this.userCallback = userCallback;
}
@Override
protected Void doInBackground(Void... params) {
ArrayList<NameValuePair> dataToSend = new ArrayList<>();
dataToSend.add(new BasicNameValuePair("firstname", user.FirstName));
dataToSend.add(new BasicNameValuePair("lastname", user.LastName));
dataToSend.add(new BasicNameValuePair("age", user.Age + ""));
dataToSend.add(new BasicNameValuePair("emailaddress", user.EmailAddress));
dataToSend.add(new BasicNameValuePair("password", user.Password));
//possible alternative code found on stack overflow don't know exactly what to do from here.
ContentValues values= new ContentValues();
values.put("firstname", user.FirstName);
values.put("lastname", user.LastName);
values.put("age", user.Age + "");
values.put("emailaddress",user.EmailAddress);
values.put("password",user.Password);
//
HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpClient post = new HttpPost(SERVER_ADDRESS + "Register.php");
try{
post.setEntity(new URLEncoderFormEntity(dataToSend));
client.execute(post);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
progressDialog.dismiss();
userCallback.done(null);
super.onPostExecute(aVoid);
}
}
public class fetchUserDataAsyncTask extends AsyncTask<Void, Void, User> {
User user;
GetUserCallback userCallback;
public fetchUserDataAsyncTask(User user, GetUserCallback userCallback) {
this.user = user;
this.userCallback = userCallback;
}
@Override
protected User doInBackground(Void... params) {
ArrayList<NameValuePair> dataToSend = new ArrayList<>();
dataToSend.add(new BasicNameValuePair("emailaddress", user.EmailAddress));
dataToSend.add(new BasicNameValuePair("password", user.Password));
HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpClient post = new HttpPost(SERVER_ADDRESS + "FetchUserData.php");
User returnedUser = null;
try{
post.setEntity(new URLEncoderFormEntity(dataToSend));
HttpResponse httpResponse = client.execute(post);
HttpEntity entity = httpResponse.getEntity();
String result = EntityUtils.toString(entity);
JSONObject jObject = new JSONObject(result);
if(jObject.length()== 0){
returnedUser = null;
} else {
String firstname = jObject.getString("firstname");
String lastname = jObject.getString("lastname");
int age = jObject.getInt("age");
returnedUser = new User(firstname, lastname, age, user.FirstName, user.LastName, user.Age);
}
}catch (Exception e){
e.printStackTrace();
}
return returnedUser;
}
@Override
protected void onPostExecute(User returnedUser) {
progressDialog.dismiss();
userCallback.done(returnedUser);
super.onPostExecute(returnedUser);
}
}
}
回答by Gagandeep Singh
You can use the following code which uses the standard java and android methods
您可以使用以下使用标准 java 和 android 方法的代码
@Override
protected Void doInBackground(Void... params) {
//Use HashMap, it works similar to NameValuePair
Map<String,String> dataToSend = new HashMap<>();
dataToSend.put("firstname", user.FirstName);
dataToSend.put("lastname", user.LastName);
dataToSend.put("age", user.Age + "");
dataToSend.put("emailaddress", user.EmailAddress);
dataToSend.put("password", user.Password);
//Server Communication part - it's relatively long but uses standard methods
//Encoded String - we will have to encode string by our custom method (Very easy)
String encodedStr = getEncodedData(dataToSend);
//Will be used if we want to read some data from server
BufferedReader reader = null;
//Connection Handling
try {
//Converting address String to URL
URL url = new URL(SERVER_ADDRESS + "Register.php");
//Opening the connection (Not setting or using CONNECTION_TIMEOUT)
HttpURLConnection con = (HttpURLConnection) url.openConnection();
//Post Method
con.setRequestMethod("POST");
//To enable inputting values using POST method
//(Basically, after this we can write the dataToSend to the body of POST method)
con.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
//Writing dataToSend to outputstreamwriter
writer.write(encodedStr);
//Sending the data to the server - This much is enough to send data to server
//But to read the response of the server, you will have to implement the procedure below
writer.flush();
//Data Read Procedure - Basically reading the data comming line by line
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while((line = reader.readLine()) != null) { //Read till there is something available
sb.append(line + "\n"); //Reading and saving line by line - not all at once
}
line = sb.toString(); //Saving complete data received in string, you can do it differently
//Just check to the values received in Logcat
Log.i("custom_check","The values received in the store part are as follows:");
Log.i("custom_check",line);
} catch (Exception e) {
e.printStackTrace();
} finally {
if(reader != null) {
try {
reader.close(); //Closing the
} catch (IOException e) {
e.printStackTrace();
}
}
}
//Same return null, but if you want to return the read string (stored in line)
//then change the parameters of AsyncTask and return that type, by converting
//the string - to say JSON or user in your case
return null;
}
The getEncodedData method (Simple to understand)
getEncodedData 方法(简单易懂)
private String getEncodedData(Map<String,String> data) {
StringBuilder sb = new StringBuilder();
for(String key : data.keySet()) {
String value = null;
try {
value = URLEncoder.encode(data.get(key),"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if(sb.length()>0)
sb.append("&");
sb.append(key + "=" + value);
}
return sb.toString();
}