I've tried searching the internet for solution unfortunately I could not find the answer. I tried using try catch to catch error exception but still it won't work.
Here's my code. I have private class LoginTask
private class LoginTask extends AsyncTask<String,String,JSONObject> {
private String[] privateCredentials;
private String privateRequest;
private String errorMessage = "";
//initialize all here
//constructor
LoginTask(String[] credentials,String request) {
this.privateRequest = request;
this.privateCredentials = credentials;
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
if(this.privateRequest=="login"){
try {
String response = result.getString("status");
if(response.equals("ok")){
onLoginSuccess(result.getString("username"),result.getString("full_name"),result.getInt("user_id"));
}else{
onLoginFails();
}
} catch (JSONException e) {
if(errorMessage!=""){
Toast ts;
ts = Toast.makeText(LoginActivity.this,errorMessage,Toast.LENGTH_LONG);
ts.show();
}
//e.printStackTrace();
}
}
}
#Override
protected JSONObject doInBackground(String... params) {
String result = "";
JSONObject resultObj = null;
HttpURLConnection con = null;
BufferedReader br = null;
JSONObject cred = new JSONObject();
if(this.privateRequest=="login"){
try {
cred.put("username", this.privateCredentials[0]);
cred.put("password", this.privateCredentials[1]);
URL url = new URL(params[0]);
con = (HttpURLConnection) url.openConnection();
;
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");
con.setRequestMethod("POST");
con.connect();
OutputStream outputStream = con.getOutputStream();
outputStream.write(cred.toString().getBytes());
InputStream stream = con.getInputStream();
br = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
buffer.append(line);
}
//get the result
JSONObject jsonObj = new JSONObject(buffer.toString());
resultObj = jsonObj;
// return buffer.toString();
}catch (JSONException e) {
errorMessage = e.getMessage();
final String error = e.getMessage();
//e.printStackTrace();
runOnUiThread(new Runnable(){
public void run() {
//ErrorDialog(e.getMessage());
Toast ts;
ts = Toast.makeText(LoginActivity.this,error,Toast.LENGTH_LONG);
ts.show();
}
});
} catch (ProtocolException e) {
errorMessage = e.getMessage();
final String error = e.getMessage();
//e.printStackTrace();
runOnUiThread(new Runnable(){
public void run() {
//ErrorDialog(e.getMessage());
Toast ts;
ts = Toast.makeText(LoginActivity.this,error,Toast.LENGTH_LONG);
ts.show();
}
});
//e.printStackTrace();
} catch (IOException e) {
errorMessage = e.getMessage();
final String error = e.getMessage();
//e.printStackTrace();
runOnUiThread(new Runnable(){
public void run() {
//ErrorDialog(e.getMessage());
Toast ts;
ts = Toast.makeText(LoginActivity.this,error,Toast.LENGTH_LONG);
ts.show();
}
});
//e.printStackTrace();
} finally {
if(con!=null) {
con.disconnect();
}
}
return resultObj;
}
return null;
}
}
And here's my event listener code in the login activity.
//when clicking the login button
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//do now the login process
userText.setVisibility(view.INVISIBLE);
passwordText.setVisibility(view.INVISIBLE);
tvRegister.setVisibility(view.INVISIBLE);
umlogo.setVisibility(view.INVISIBLE);
//set textviews to invisible
/* tv[0].setVisibility(view.INVISIBLE);
tv[1].setVisibility(view.INVISIBLE);*/
//set also the button to invisible
loginBtn.setVisibility(view.INVISIBLE);
//set visible the progress bar
pb.setVisibility(view.VISIBLE);
//set now the user login credentials
credentials[0] = userText.getText().toString();
credentials[1] = passwordText.getText().toString();
loginTask = new LoginTask(credentials,"login");
//loginTask.execute("http://10.0.2.2/sampleRequest.php");
//loginTask.execute("http://10.0.2.2/motorpool_june_2016_laravel/public/mobile/login");
loginTask.execute("http://128.199.105.49/mobile/login");
//SessionHolder.login(credentials, la);
}
});
However it is still not working. Please help. :(
You can't compare Strings with == in java. You must write it like below:
if(this.privateRequest.equals("login")){
== tests for reference equality (whether they are the same object)
Related
I try to create synchronized threads, but I always get the following error: android.os.NetworkOnMainThreadException.
I've read more posts, but they don't work for me.
Below I write the code blocks that do not work for me:
1.
final SyncApp syncJob = new SyncApp();
Thread t = new Thread (new Runnable () {
#Override
public void run () {
synchronized (syncJob) {
String s = syncJob.insert (newJobs, GlobalVariables.URL_LOCALHOST + "jobs");
txtState.setText (s);
}}});
}
});
t.Start ();
// t.run ();
2.
myClass.runOnUiThread(new Runnable() {
public void run() {...}
})
3.
Running code in main thread from another thread
SyncApp:
public class SyncApp {
synchronized public String insert(List<Jobs> job, String... params) {
URL url = null;
HttpURLConnection conn = null;
try {
url = new URL(params[0]);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoInput(true);
conn.setDoOutput(true);
String str = new Gson().toJson(job);
byte[] outputInBytes = str.getBytes();
OutputStream os = conn.getOutputStream();
os.write( outputInBytes );
os.flush();
int responseCode=conn.getResponseCode();
String response = null;
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
}
}
else {
response=conn.getResponseMessage();
}
return response;
} catch (Exception e) {
e.printStackTrace();
} finally {
conn.disconnect();
}
return null;
}
}
I need to call a thread, wait for the answer and call another thread. Their answers I must use them in the activity
I need to call a thread, wait for the answer and call another thread.
Their answers I must use them in the activity
Example using async tasks to accomplish objective.
In this code, let A be your activity which needs to call a thread,
wait for the answer and call another thread. Customize as needed.
Since you never wait in UI threads, callbacks are used to accomplish synchronization.
Let A be your activity class:
public class A extends Activity {
// some method in activity where you launch a background thread (B)
// which then completes and invokes callback which then creates and launches
// a background thread (C) which then completes and invokes a callback.
//
// In callback C, you are on the UI thread.
protected void someMethod() {
new B(new B.CallbackB() {
public void result(Object o) {
new C(new C.CallbackC() {
public void result(Object o, Object answerFromB) {
// OK - C is now done and we are on UI thread!
// 'o' is answer from C
// 'answerFromB' also provided
}
}, o).execute(new Object());
}
).execute(new Object());
}
}
Define a class B:
public class B extends AsyncTask<Object, Void, Object> {
public static interface CallbackB {
void result(Object o);
}
private CallbackB cb;
public B (CallbackB cb) {
this.cb = cb;
}
protected Object doInBackground(Object... params) {
// do work and return an answer.
return new Object();
}
protected void onPostExecute(Object result) {
if (cb != null) {
cb.result(result);
}
}
}
Define a class C:
public class C extends AsyncTask<Object, Void, Object> {
public static interface CallbackC {
void result(Object o, Object answerFromB);
}
private CallbackC cb;
private Object answerFromB;
public C (CallbackC cb, Object answerFromB) {
this.cb = cb;
this.answerFromB = answerFromB;
}
protected Object doInBackground(Object... params) {
// do work and return an answer.
return new Object();
}
protected void onPostExecute(Object result) {
if (cb != null) {
cb.result(result, answerFromB);
}
}
}
For reference:
https://stackoverflow.com/a/9963705/2711811
My solution is:
public class Sync extends AppCompatActivity {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sync_server);
dao = new DAO(this);
txtState = findViewById(R.id.txt_log);
btnSincro = findViewById(R.id.btn_sincro);
btnSincro.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
countCall = 0;
callFlow();
}
});
btnHome = findViewById(R.id.btn_home);
btnHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SyncServerActivity.this, MainActivity.class);
startActivity(intent);
}
});
}
private void callFlow() {
switch (countCall) {
case 0:
templates = toTemplate("url");
break;
case 1:
jobs = toJobs("url");
break;
case 2:
job = ... //select item
res = sendJobs(jobs, "url");
break;
default:
runOnUiThread(new Runnable() {
#Override
public void run() {
btnSincro.setEnabled(true);
txtState.append("\n\nEND");
}
});
}
}
private void nextStep() {
setText(txtState, "\nSync \n" + countCall + "/3");
countCall++;
callFlow();
}
private void setText(final TextView text, final String value) {
runOnUiThread(new Runnable() {
#Override
public void run() {
text.setText(value);
}
});
}
public List<Templates> toTemplate(final String... params) {
final List<Templates> list = new ArrayList<>();
Thread t = new Thread(new Runnable() {
#Override
public void run() {
URL url = null;
BufferedReader reader = null;
HttpURLConnection connection = null;
try {
url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
int responseCode = connection.getResponseCode();
String response = null;
if (responseCode == HttpsURLConnection.HTTP_OK) {
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("data");
for (int i = 0; i < parentArray.length(); i++) {
Templates item = new Gson().fromJson(parentArray.get(i).toString(), Templates.class);
list.add(item);
}
} else {
response = connection.getResponseMessage();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
try {
if (reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
nextStep(); //call next Thread
}
}
});
t.start();
return list;
}
public List<Jobs> toJobs(final String... params) {
final List<Jobs> list = new ArrayList<>();
Thread t = new Thread(new Runnable() {
#Override
public void run() {
URL url = null;
BufferedReader reader = null;
HttpURLConnection connection = null;
try {
url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
int responseCode = connection.getResponseCode();
String response = null;
if (responseCode == HttpsURLConnection.HTTP_OK) {
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("data");
for (int i = 0; i < parentArray.length(); i++) {
Jobs item = new Gson().fromJson(parentArray.get(i).toString(), Jobs.class);
list.add(item);
}
} else {
response = connection.getResponseMessage();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
try {
if (reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
nextStep();
}
}
});
t.start();
return list;
}
public Boolean sendJobs(final List<Jobs> job, final String... params) {
final Boolean[] result = {false};
Thread t = new Thread(new Runnable() {
#Override
public void run() {
URL url = null;
HttpURLConnection conn = null;
try {
url = new URL(params[0]);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoInput(true);
conn.setDoOutput(true);
String str = new Gson().toJson(job);
Log.d(TAG, str);
byte[] outputInBytes = str.getBytes();
OutputStream os = conn.getOutputStream();
os.write(outputInBytes);
os.flush();
int responseCode = conn.getResponseCode();
String response = null;
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
result[0] = true;
} else {
response = conn.getResponseMessage();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
conn.disconnect();
nextStep();
}
}
});
t.start();
return result[0];
}
}
Whenever a thread ends, it calls the nextStep() method, which starts the next trhead.
I am so beginner about Json. I am trying to understand example on the internet. So that I am doing a translater for myself(Yandex translater). But I have problem I copied and pasted source cod to my project. To making When I clicked my button , Text will be my textview(being translated) Now I cannot get translated string for my textview.How can I get it ?
My TranslatorBackgroundTask AsyncTask (it is not inner class) :
TranslatorBackgroundTask(Context ctx){
this.ctx = ctx;
}
#Override
protected String doInBackground(String... params) {
//String variables
String textToBeTranslated = params[0];
String languagePair = params[1];
String jsonString;
try {
//Set up the translation call URL
String yandexKey =
String yandexUrl = "https://translate.yandex.net/api/v1.5/tr.json/translate?key=" + yandexKey
+ "&text=" + textToBeTranslated + "&lang=" + languagePair;
URL yandexTranslateURL = new URL(yandexUrl);
//Set Http Conncection, Input Stream, and Buffered Reader
HttpURLConnection httpJsonConnection = (HttpURLConnection) yandexTranslateURL.openConnection();
InputStream inputStream = httpJsonConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
//Set string builder and insert retrieved JSON result into it
StringBuilder jsonStringBuilder = new StringBuilder();
while ((jsonString = bufferedReader.readLine()) != null) {
jsonStringBuilder.append(jsonString + "\n");
}
//Close and disconnect
bufferedReader.close();
inputStream.close();
httpJsonConnection.disconnect();
//Making result human readable
String resultString = jsonStringBuilder.toString().trim();
//Getting the characters between [ and ]
resultString = resultString.substring(resultString.indexOf('[')+1);
resultString = resultString.substring(0,resultString.indexOf("]"));
//Getting the characters between " and "
resultString = resultString.substring(resultString.indexOf("\"")+1);
resultString = resultString.substring(0,resultString.indexOf("\""));
Log.d("Translation Result:", resultString);
return jsonStringBuilder.toString().trim() ;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
My MainActivity :
cevir_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String yazı_string = yazı_EditText.getText().toString();
// trans(yazı_string,language);
String languagePair = "en-fr";
Translate(yazı_string,languagePair);
}
});
private void Translate(String textToBeTranslated, String languagePair) {
TranslatorBackgroundTask translatorBackgroundTask= new TranslatorBackgroundTask(context);
AsyncTask<String, Void, String> translationResult = translatorBackgroundTask.execute(textToBeTranslated,languagePair);
try {
String translationResults = translatorBackgroundTask.execute(textToBeTranslated, languagePair).get();
cevirilmis_tTextView.setText(translationResults);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
Log.d("Translation Result", String.valueOf(translationResult));
}
You could simply get the string from the AsyncTask:
String translationResult = translatorBackgroundTask.execute(textToBeTranslated, languagePair).get();
However this approach defeats the point of using an AsyncTask as you will end up blocking the UI thread as you wait for the result from .get(). Instead you should use a callback like this
I would like to retrieve the contents of my variable "$content" in my activity.
But I don't know how to use the return value of my doinbackground.
Can you help me ?
thank you in advance
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String restURL = "https://proxyepn-test.epnbn.net/wsapi/epn";
RestOperation test = new RestOperation();
test.execute(restURL);
}
private class RestOperation extends AsyncTask<String, Void, String> {
//final HttpClient httpClient = new DefaultHttpClient();
String content;
String error;
ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
String data = "";
TextView serverDataReceived = (TextView)findViewById(R.id.serverDataReceived);
TextView showParsedJSON = (TextView) findViewById(R.id.showParsedJSON);
// EditText userinput = (EditText) findViewById(R.id.userinput);
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.setTitle("Please wait ...");
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
BufferedReader br = null;
URL url;
try {
url = new URL(params[0]);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter outputStreamWr = new OutputStreamWriter(connection.getOutputStream());
outputStreamWr.write(data);
outputStreamWr.flush();
br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while((line = br.readLine())!=null) {
sb.append(line);
sb.append(System.getProperty("line.separator"));
}
content = sb.toString();
} catch (MalformedURLException e) {
error = e.getMessage();
e.printStackTrace();
} catch (IOException e) {
error = e.getMessage();
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return content;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
if(error!=null) {
serverDataReceived.setText("Error " + error);
} else {
serverDataReceived.setText(content);
String output = "";
JSONObject jsonResponse;
try {
jsonResponse = new JSONObject(content);
JSONArray jsonArray = jsonResponse.names();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject child = jsonArray.getJSONObject(i);
String name = child.getString("name");
String number = child.getString("number");
String time = child.getString("date_added");
output = "Name = " + name + System.getProperty("line.separator") + number + System.getProperty("line.separator") + time;
output += System.getProperty("line.separator");
Log.i("content",content);
}
showParsedJSON.setVisibility(View.INVISIBLE);
showParsedJSON.setText(output);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
You can directly call to the method which exist in activity, from onPostExecute method of asynctask by passing "content" value.
#Override
protected void onPostExecute(String content) {
Activity.yourMethod(content);
}
If you want to return the value from asynctask you can use
content = test.execute(url).get();
but it is not a good practice of asynctask, because it is working as serial execution. So it is not fulfill the use of asynctask for palatalization.Because get() will block the UI thread.
Here is my android rest request code but the where i get the url from edit text using its id but "getString" gets flagged(can't be resolved). Please help
class RESTRequest
{
//final String ADD_STROKE_URL = "";
final String ADD_STROKE_URL = new String[]{ getString(R.id.buttonUploadURL)};
public Boolean success = null;
private JSONObject params;
private String strokeId;
private HashSet<Point> localPoints;
private StrokeManagerCallback callback;
public static String encode(Object x) {
try {
return URLEncoder.encode(String.valueOf(x),"UTF-8");
} catch (UnsupportedEncodingException e) {
return(String.valueOf(x));
}
}
public RESTRequest(JSONObject params,String strokeId,Set<Point> points,StrokeManagerCallback callback)
{
this.params = params;
this.strokeId = strokeId;
this.localPoints = new HashSet<Point>();
this.localPoints.addAll(points);
this.callback = callback;
new ExecuteREST().execute();
}
private class ExecuteREST extends AsyncTask<Void, Void, String>
{
protected String doInBackground(Void ...arg0)
{
/* Build URL query */
StringBuffer local = new StringBuffer(ADD_STROKE_URL);
if(params != null)
{
local.append("?");
Iterator<?> k = params.keys();
while(k.hasNext()){
try {
String key = (String) k.next();
Object value = params.get(key);
local.append(encode(key));
local.append("=");
local.append(encode(value));
if(k.hasNext()){
local.append("&");
}
}
catch (JSONException e) {e.printStackTrace();}
}
}
HttpURLConnection urlConn = null;
StringBuffer response = new StringBuffer("error");
try
{
URL url = new URL(local.toString());
urlConn = (HttpURLConnection) url.openConnection();
urlConn.setRequestMethod("GET");
urlConn.setDoInput(true);
urlConn.setUseCaches(false);
urlConn.setRequestProperty("Content-Type", "application/json");
urlConn.connect();
//Get Response
InputStream is = urlConn.getInputStream();
BufferedReader rd = new BufferedReader(newInputStreamReader(is));
String line;
response = new StringBuffer();
try{
while((line = rd.readLine()) != null) {
response.append(line);
}
}
finally{
if(urlConn != null){
urlConn.disconnect();
urlConn = null;
}
if(rd != null){
rd.close();
rd = null;
}
}
if(callback != null){
callback.onSuccess(strokeId, localPoints);
}
} catch (ConnectException e) {
callback.onFailure(strokeId, localPoints);
} catch (UnknownHostException e) {
callback.onFailure(strokeId, localPoints);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (EOFException e) {
response = new StringBuffer("No response from server");
} catch (IOException e) {
e.printStackTrace();
} catch (RuntimeException e) {
e.printStackTrace();
}
finally{
if(urlConn != null){
urlConn.disconnect();
}
}
return response.toString();
}
}
you can get String Resources like this
Resources res = context.getResources();
final String ADD_STROKE_URL = new String[]{ res.getString(R.id.buttonUploadURL)};
and now you can pass that url in AcycncTask class like this
public RESTRequest(JSONObject params,String
strokeId,Set<Point>points,StrokeManagerCallback callback){
this.params = params;
this.strokeId = strokeId;
this.localPoints = new HashSet<Point>();
this.localPoints.addAll(points);
this.callback = callback;
new ExecuteREST(/*Pass url here that you will get in doInBackground method */)
.execute();
}
private class ExecuteREST extends AsyncTask<String, Void, String>{
protected String doInBackground(String ...arg0){
//get your url in arg0 variable
StringBuffer local = new StringBuffer(arg0[0]);
.
.
.
//Rest of yours ...
I am trying to get my webview to show a page that is only accesible after i am logged in. but whatever i try i cant get past the login url.
How can i open/show the SEND_VISUM_URL after i login.
this is what i have so far:
String LOGIN_URL = "http://10.35.50.125/BCS/index.php?module=";
String SEND_VISUM_URL = "http://10.35.50.1/BCS/index.php?module=ScanVisa&Action=save";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView)findViewById(R.id.webviewer);
webView.loadUrl(LOGIN_URL);
cookieManager = new CookieManager();
Button login = (Button) findViewById(R.id.PostData);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
new loginTask().execute(getLoginData());
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
}
public class loginTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
String loginData = params[0];
String text = "";
BufferedReader reader = null;
// Send data
try {
// Defined URL where to send data
URL login_url = new URL(LOGIN_URL);
// getting cookies:
URLConnection conn = login_url.openConnection();
conn.connect();
// setting cookies
cookieManager.storeCookies(conn);
cookieManager.setCookies(login_url.openConnection());
cookiestring = cookieManager.toString();
Log.d("Cookie in logintask:", cookiestring);
conn.getContent();
conn.setDoOutput(true);
conn.setConnectTimeout(3000);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
try {
wr.write(loginData); //post
wr.flush();
} catch (Exception e) {
e.printStackTrace();
}
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
if (line.length() > 0) {
sb.append(line + "\n");
if (line == null) {
continue;
}
}
}
text = sb.toString();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (reader != null) reader.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
return text;
}
protected void onPostExecute(String line) {
if (!line.contains("I107")) { //I107 is an error code that is returend when a login failed
Toast.makeText(getBaseContext(), "Login succesfull", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(), "Login failed", Toast.LENGTH_LONG).show();
}
}
}
public void setCookies(URLConnection conn) throws IOException {
// let's determine the domain and path to retrieve the appropriate cookies
URL url = conn.getURL();
String domain = getDomainFromHost(url.getHost());
String path = url.getPath();
Map domainStore = (Map)store.get(domain);
if (domainStore == null) return;
StringBuffer cookieStringBuffer = new StringBuffer();
Iterator cookieNames = domainStore.keySet().iterator();
while(cookieNames.hasNext()) {
String cookieName = (String)cookieNames.next();
Map cookie = (Map)domainStore.get(cookieName);
// check cookie to ensure path matches and cookie is not expired
// if all is cool, add cookie to header string
if (comparePaths((String)cookie.get(PATH), path) && isNotExpired((String)cookie.get(EXPIRES))) {
cookieStringBuffer.append(cookieName);
cookieStringBuffer.append("=");
cookieStringBuffer.append((String)cookie.get(cookieName));
if (cookieNames.hasNext()) cookieStringBuffer.append(SET_COOKIE_SEPARATOR);
}
}
try {
conn.setRequestProperty(COOKIE, cookieStringBuffer.toString());
} catch (java.lang.IllegalStateException ise) {
IOException ioe = new IOException("Illegal State! Cookies cannot be set on a URLConnection that is already connected. "
+ "Only call setCookies(java.net.URLConnection) AFTER calling java.net.URLConnection.connect().");
throw ioe;
}
}
any help would be greatly appreciated!