如何在 AsyncTask 或 RequestHandler.java 中添加基本的 auth java android?
Posted
技术标签:
【中文标题】如何在 AsyncTask 或 RequestHandler.java 中添加基本的 auth java android?【英文标题】:How to add basic auth java android in AsyncTask or RequestHandler.java? 【发布时间】:2018-01-21 08:32:50 【问题描述】:我的问题是如何添加基本的身份验证 Java android AsyncTask?一些开发人员说它需要在RequestHandler.java
或doInBackground AsyncTask
函数中声明。以下是我的代码:
private void loginTask(String _username, String _password)
final String username = _username;
final String password = _password;
class LoginTask extends AsyncTask<Void,Void,String>
ProgressDialog loading;
@Override
protected void onPreExecute()
super.onPreExecute();
loading = ProgressDialog.show(LoginActivity.this,"Fetching...","Wait...",false,false);
@Override
protected void onPostExecute(String s)
super.onPostExecute(s);
loading.dismiss();
@Override
protected String doInBackground(Void... params)
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequest(App.URL_AUTHENTICATION);
Toast.makeText(LoginActivity.this, s.toString(), Toast.LENGTH_SHORT).show();
return s;
LoginTask gt = new LoginTask();
gt.execute();
RequestHandler 类:https://github.com/IntellijSys/AndroidToDoList/blob/master/app/src/main/java/my/intellij/androidtodolist/RequestHandler.java
【问题讨论】:
这段代码不会编译,你不能在一个方法中创建一个类,而且你的用户名和密码变量是多余的,你的 toast 应该是在onPostExecute
上调用的,最后这是一个泄漏的实现因为您的 asynctask 将包含对您的父类的隐式引用,因此请考虑使用 WeakReference
或避免 AsyncTask 的非静态内部类。
我会调整的那个。对于基本身份验证,仍然没有任何想法。
【参考方案1】:
试试这个
RequestHandler rh = new RequestHandler();
// your basic auth username and password
rh.setBasicAuth("username","password");
String s = rh.sendGetRequest(App.URL_AUTHENTICATION);
具有基本身份验证的 RequestHandler 类
import android.util.Base64;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
/**
* Created by ZERO on 16/08/2016.
*/
public class RequestHandler
private String username;
private String password;
//Method to send httpPostRequest
//This method is taking two arguments
//First argument is the URL of the script to which we will send the request
//Other is an HashMap with name value pairs containing the data to be send with the request
public String sendPostRequest(String requestURL,
HashMap<String, String> postDataParams)
URL url;
//StringBuilder object to store the message retrieved from the server
StringBuilder sb = new StringBuilder();
try
//Initializing Url
url = new URL(requestURL);
//Creating an httmlurl connection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//set Basic auth
processBasicAuth(conn);
//Configuring connection properties
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
//Creating an output stream
OutputStream os = conn.getOutputStream();
//Writing parameters to the request
//We are using a method getPostDataString which is defined below
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK)
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
sb = new StringBuilder();
String response;
//Reading server response
while ((response = br.readLine()) != null)
sb.append(response);
catch (Exception e)
e.printStackTrace();
return sb.toString();
private void processBasicAuth(HttpURLConnection conn)
if (username != null && password != null)
try
String userPassword = username + ":" + password;
byte[] data = userPassword.getBytes("UTF-8");
String base64 = Base64.encodeToString(data, Base64.DEFAULT);
conn.setRequestProperty("Authorization", "Basic " + base64);
catch (UnsupportedEncodingException e)
e.printStackTrace();
public String sendGetRequest(String requestURL)
StringBuilder sb = new StringBuilder();
try
URL url = new URL(requestURL);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
//set Basic auth
processBasicAuth(con);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String s;
while ((s = bufferedReader.readLine()) != null)
sb.append(s + "\n");
catch (Exception e)
return sb.toString();
public String sendGetRequestParam(String requestURL, String id)
StringBuilder sb = new StringBuilder();
try
URL url = new URL(requestURL + id);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String s;
while ((s = bufferedReader.readLine()) != null)
sb.append(s + "\n");
catch (Exception e)
return sb.toString();
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet())
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
return result.toString();
public void setBasicAuth(String username, String password)
this.username = username;
this.password = password;
【讨论】:
我先试试 这段代码rh.setBasicAuth("username","password");
只是设置了变量,但之后它什么也不做。您需要在 setBasicAuth
方法中添加更多内容。
@Enzokie 看这里 //set Basic auth processBasicAuth(conn);
是的,但它如何与 processBasicAuth() 交互?
@MohammadNurdin 当你调用 sendGetRequest();以上是关于如何在 AsyncTask 或 RequestHandler.java 中添加基本的 auth java android?的主要内容,如果未能解决你的问题,请参考以下文章
AsyncTask 执行()或 executeOnExecutor()?
Async Json 提要晚于 AsyncTask 完成以从 sqlite DB 加载数据。如何同步它们或更好的解决方案?