我想用webview构建一个app android, 我希望webview应用程序能够使用http-post方法自动登录我发送的参数。 我参考了这个: Logging in via HttpPost to a website via an application
但仍然无法登录到我的网站,它总是向我显示登录表单,我应该发送帖子数据到: android.erfolgmedia.com/new_login/log.php?act=in 并发送电子邮件和密码通过http发布的webview android,
这是我的代码:
url = "http://android.erfolgmedia.com/new_login/log.php?act=in";
String login_tag = "login";
String email = "adi@erfolgmedia.com";
String pass = "adiadi";
try{
List<NameValuePair> params2 = new ArrayList<NameValuePair>();
params2.add(new BasicNameValuePair("tag", login_tag));
params2.add(new BasicNameValuePair("email", email));
params2.add(new BasicNameValuePair("password", pass));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(params2, HTTP.UTF_8));
HttpResponse response = httpclient.execute(httppost);
String data = new BasicResponseHandler().handleResponse(response);
webView = (WebView) findViewById(R.id.webView1);
webView.setWebViewClient(new HelloWebViewClient());
webView.loadDataWithBaseURL(httppost.getURI().toString(), data, "text/html", HTTP.UTF_8, null);
webView.getSettings().setJavaScriptEnabled(true);
String postData = "tag" + "=" + login_tag + "&" + "email" + "=" + email + "&" + "password" + "=" + pass;
webView.postUrl(url, EncodingUtils.getBytes(postData, "utf-8"));
}catch(Exception e){
e.printStackTrace();
}
//openBrowser();
}
感谢您的时间!我真的很感谢你看看我的问题。
答案 0 :(得分:0)
我曾经在下面上课。我不知道它是否是最新的,所以你可能需要稍微调整一下。您可以使用以下方式调用它:
RestWrapperAsync wrapper = new RestWrapperAsync();
wrapper.SetUp("url");
wrapper.setFormBodyJson(jsonArray); //or setform..
wrapper.SetAuthentication("name", "password");
wrapper.SetResponseCallback(this);
wrapper.execute();
public class RestWrapperAsync extends AsyncTask<Void, Integer, Object> {
private WeakReference<ResponseCallback> mResponseCallback;
private WeakReference<ProgressCallback> mProgressCallback;
public interface ResponseCallback {
public void OnRequestSuccess(String response);
public void OnRequestError(Exception ex);
}
public interface ProgressCallback {
public void OnProgressUpdate(int progress);
}
public void SetResponseCallback(ResponseCallback callback){
mResponseCallback = new WeakReference<ResponseCallback>(callback);
}
public void setProgressCallback(ProgressCallback callback) {
mProgressCallback = new WeakReference<ProgressCallback>(callback);
}
private boolean getDetailsFromPost = false;
public void SetGetDetailsFromPost(boolean value){
getDetailsFromPost = value;
}
HttpURLConnection mConnection;
String mFormBody;
File mUploadFile;
String mUploadFileName;
JSONArray mFormBodyJSONArray;
JSONObject mFormBodyJSON;
/**
* Sets up the connection and the url
* @param siteUrl
*/
public void SetUp(String siteUrl, boolean doOutput){
try
{
URL url=null;
if (siteUrl!=null) {
url = new URL(siteUrl);
}
else {
url = new URL("https://xxxx");
}
mConnection = (HttpURLConnection) url.openConnection();
mConnection.setReadTimeout(10000 /* milliseconds */);
mConnection.setConnectTimeout(5000 /* milliseconds */);
mConnection.setRequestMethod("GET"); //set to get initially
if (doOutput){
//mConnection.setDoOutput(true);
mConnection.setDoInput(true);
}
else
mConnection.setDoInput(true);
}
catch (Exception ex){
Log.e("ERROR","Exception setting up connection:"+ex.getMessage());
}
}
/**
* Sets up form body for post requests
* @param formData
*/
public void setFormBody(List<NameValuePair> formData){
if (formData == null) {
mFormBody = "";
return;
}
try
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < formData.size(); i++) {
NameValuePair item = formData.get(i);
sb.append( URLEncoder.encode(item.getName(),"UTF-8") );
sb.append("=");
sb.append( URLEncoder.encode(item.getValue(),"UTF-8") );
if (i != (formData.size() - 1)) {
sb.append("&");
}
}
mFormBody = sb.toString();
}
catch(Exception ex){
Log.e("ERROR","Exception setting up connection:"+ex.getMessage());
}
}
/**
* Sets up form body for post request
* @param object
*/
public void setFormBodyJson(JSONArray object){
mFormBodyJSONArray = object;
}
/**
* Sets up form body for post request
* @param object
*/
public void setFormBodyJson(JSONObject object){
mFormBodyJSON = object;
}
/**
* Write out Json array to outputstream
* @param charset
* @param output
* @throws IOException
*/
private void writeFormDataJSON(JSONArray charset, OutputStream output) throws IOException {
try
{
output.write(charset.toString().getBytes());
output.flush();
}
finally
{
if (output != null) {
output.close();
}
}
}
/**
* Write out Json object to outputstream
* @param charset
* @param output
* @throws IOException
*/
private void writeFormDataJSON(JSONObject charset, OutputStream output) throws IOException {
try
{
output.write(charset.toString().getBytes());
output.flush();
}
finally
{
if (output != null) {
output.close();
}
}
}
/**
* Write out Charset to outputStream
* @param charset
* @param output
* @throws IOException
*/
private void writeFormData(String charset, OutputStream output) throws IOException {
try
{
output.write(mFormBody.getBytes(charset));
output.flush();
}
finally
{
if (output != null) {
output.close();
}
}
}
/**
* Sets up authentication
* @param username
* @param password
*/
public void SetAuthentication(String username, String password){
if (this.mConnection==null) {
Log.e("RestWrapper","Autentication called, but connection = null");
}
else
attachBasicAuthentication(mConnection,username,password);
}
/**
* Attaches authorization to header
* @param connection
* @param username
* @param password
*/
private static void attachBasicAuthentication(URLConnection connection, String username, String password) {
//Add Basic Authentication Headers
String userpassword = username + ":" + password;
String encodedAuthorization =
Base64.encodeToString(userpassword.getBytes(), Base64.NO_WRAP);
connection.setRequestProperty("Authorization", "Basic "+ encodedAuthorization);
}
public void setUploadFile(File file, String fileName) {
mUploadFile = file;
mUploadFileName = fileName;
}
/**
* Do network connection in background
*/
@Override
protected Object doInBackground(Void... arg0) {
return CallService(true);
}
/**
* The actual call to the web api's
* @param isAsyn
* @return
*/
public Object CallService(boolean isAsyn){
try
{
String charset = Charset.defaultCharset().displayName();
if (mFormBodyJSON != null) {
mConnection.setDoOutput(true);
mConnection.setRequestMethod("POST");
mConnection.setRequestProperty("Content-Type","application/json; charset="+charset);
mConnection.setFixedLengthStreamingMode(mFormBodyJSON.toString().length());
}
else if (mFormBodyJSONArray != null) {
mConnection.setDoOutput(true);
mConnection.setRequestMethod("POST");
mConnection.setRequestProperty("Content-Type","application/json; charset="+charset);
mConnection.setFixedLengthStreamingMode(mFormBodyJSONArray.toString().length());
}
else if (mFormBody != null) {
mConnection.setDoOutput(true);
mConnection.setRequestMethod("POST"); //change to post
mConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset="+charset);
mConnection.setFixedLengthStreamingMode(mFormBody.length());
}
if (isAsyn)
this.publishProgress(1);
mConnection.connect();
if (mFormBodyJSON!=null){
OutputStream out = mConnection.getOutputStream();
writeFormDataJSON(mFormBodyJSON, out);
}
else if (mFormBodyJSONArray!=null){
OutputStream out = mConnection.getOutputStream();
writeFormDataJSON(mFormBodyJSONArray, out);
}
else if (mFormBody != null) {
OutputStream out = mConnection.getOutputStream();
writeFormData(charset, out);
}
int status=0;
status = mConnection.getResponseCode();
if (isAsyn)
this.publishProgress(2);
if (status == 204){
if (!getDetailsFromPost){
return Constants.DATAPOSTEDCORRECTLY;
}
}
if (status >= 300){
String message = mConnection.getResponseMessage();
InputStream in = mConnection.getErrorStream();
String encoding = mConnection.getContentEncoding();
if (encoding == null) {
encoding = "UTF-8";
}
if (in != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(in, encoding));
message = reader.readLine();
message = message.replace('"', ' ');
message = message.trim();
return new HttpResponseException(status, message);
}
}
//Get response data back
InputStream in = mConnection.getInputStream();
String encoding = mConnection.getContentEncoding();
if (encoding == null) {
encoding = "UTF-8";
}
this.publishProgress(3);
BufferedReader reader = new BufferedReader(new InputStreamReader(in, encoding));
String result = reader.readLine();
return result;
}
catch (Exception ex){
return ex;
}
finally {
if (mConnection != null) {
mConnection.disconnect();
}
}
}
@Override
protected void onProgressUpdate(Integer... values) {
if (mProgressCallback != null && mProgressCallback.get() != null) {
mProgressCallback.get().OnProgressUpdate(values[0]);
}
}
@Override
protected void onPostExecute(Object result) {
if (mResponseCallback != null && mResponseCallback.get() != null) {
if (result instanceof String) {
mResponseCallback.get().OnRequestSuccess((String) result);
}
else if (result instanceof Exception) {
mResponseCallback.get().OnRequestError((Exception) result);
}
else {
mResponseCallback.get().OnRequestError(new IOException("Unknown Error Contacting Host"));
}
mResponseCallback = null;
mProgressCallback = null;
}
}
}