如何在AsyncTask或RequestHandler.java中添加基本身份验证java android?
我的问题是如何添加基本身份验证Java Android异步任务?一些开发人员说它需要在如何在AsyncTask或RequestHandler.java中添加基本身份验证java android?,java,android,android-asynctask,Java,Android,Android Asynctask,我的问题是如何添加基本身份验证Java Android异步任务?一些开发人员说它需要在RequestHandler.java或doinbackgroundasynctask函数中声明。下面是我的代码: private void loginTask(String _username, String _password){ final String username = _username; final String password = _password;
RequestHandler.java
或doinbackgroundasynctask
函数中声明。下面是我的代码:
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();
}
private void登录任务(字符串\u用户名,字符串\u密码){
最终字符串用户名=_用户名;
最终字符串密码=_密码;
类LoginTask扩展了异步任务{
对话加载;
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
loading=ProgressDialog.show(LoginActivity.this,“获取…”,“等待…”,false,false);
}
@凌驾
受保护的void onPostExecute(字符串s){
super.onPostExecute(s);
loading.dispose();
}
@凌驾
受保护字符串doInBackground(无效…参数){
RequestHandler rh=新的RequestHandler();
字符串s=rh.sendGetRequest(App.URL\u身份验证);
Toast.makeText(LoginActivity.this,s.toString(),Toast.LENGTH_SHORT.show();
返回s;
}
}
LoginTask gt=新的LoginTask();
gt.execute();
}
RequestHandler类:试试这个
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;
}
}
导入android.util.Base64;
导入java.io.BufferedReader;
导入java.io.BufferedWriter;
导入java.io.InputStreamReader;
导入java.io.OutputStream;
导入java.io.OutputStreamWriter;
导入java.io.UnsupportedEncodingException;
导入java.net.HttpURLConnection;
导入java.net.URL;
导入java.net.urlcoder;
导入java.util.HashMap;
导入java.util.Map;
导入javax.net.ssl.HttpsURLConnection;
/**
*由ZERO于2016年8月16日创建。
*/
公共类RequestHandler{
私有字符串用户名;
私有字符串密码;
//发送httpPostRequest的方法
//此方法包含两个参数
//第一个参数是我们将向其发送请求的脚本的URL
//另一个是名值对的HashMap,其中包含要随请求发送的数据
公共字符串sendPostRequest(字符串请求URL,
HashMap postDataParams){
网址;
//StringBuilder对象来存储从服务器检索到的消息
StringBuilder sb=新的StringBuilder();
试一试{
//初始化Url
url=新url(请求url);
//创建httmlurl连接
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
//设置基本身份验证
工艺基础(康涅狄格州);
//配置连接属性
连接设置读取超时(15000);
连接设置连接超时(15000);
conn.setRequestMethod(“POST”);
conn.setDoInput(真);
连接设置输出(真);
//创建输出流
OutputStream os=conn.getOutputStream();
//将参数写入请求
//我们正在使用下面定义的getPostDataString方法
BufferedWriter=新的BufferedWriter(
新的OutputStreamWriter(操作系统,“UTF-8”);
write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
if(responseCode==HttpsURLConnection.HTTP\u确定){
BufferedReader br=新的BufferedReader(新的InputStreamReader(conn.getInputStream());
sb=新的StringBuilder();
字符串响应;
//读取服务器响应
而((response=br.readLine())!=null){
某人追加(答复);
}
}
}捕获(例外e){
e、 printStackTrace();
}
使某人返回字符串();
}
私有void processBasicAuth(HttpURLConnection){
如果(用户名!=null和密码!=null){
试一试{
字符串userPassword=用户名+“:”+密码;
byte[]data=userPassword.getBytes(“UTF-8”);
字符串base64=base64.encodeToString(数据,base64.DEFAULT);
conn.setRequestProperty(“授权”、“基本”+base64);
}捕获(不支持的编码异常e){
e、 printStackTrace();
}
}
}
公共字符串sendGetRequest(字符串请求URL){
StringBuilder sb=新的StringBuilder();
试一试{
URL=新URL(请求URL);
HttpURLConnection con=(HttpURLConnection)url.openConnection();
//设置基本身份验证
工艺基础(con);
BufferedReader BufferedReader=新的BufferedReader(新的InputStreamReader(con.getInputStream());
字符串s;
而((s=bufferedReader.readLine())!=null){
sb.追加(s+“\n”);
}
}捕获(例外e){
}
使某人返回字符串();
}
公共字符串sendGetRequestParam(字符串requestURL,字符串id){
StringBuilder sb=新的StringBuilder();
试一试{
URL=新URL(请求URL+id);
HttpURLConnection con=(HttpURLConnection)url.openConnection();
BufferedReader BufferedReader=新的BufferedReader(新的InputStreamReader(con.getInputStream());
字符串s;
而((s=bufferedReader.readLine())!=null){
sb.追加(s+“\n”);
}
}捕获(例外e){
}
使某人返回字符串();
}
私有字符串getPostDataString(HashMap参数)引发UnsupportedEncodingException{
StringBuilder结果=新建StringBuilder();
布尔值优先=真;
对于(Map.Entry:params.Entry