Android - How can I get the email from the online login and show it to next intent - android-asynctask

I created an online login on my mobile app, basically I have an online database, and I use asynctask for login. Basically I want to display the email that the user input from the app and display it to the next intent how can I do that, How can I pass the email that the user input to onPostExecute?
Here is the code in the onPostExecute when the user successfully logged in.
protected void onPostExecute(String result)
{
if (result.equals("Login Successfully!")) {
Toast.makeText(context, "Welcome to OKShop", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, Main2Activity.class);
context.startActivity(intent);
((Activity)context).finish();
}
}
And here is the login URL
else if (type.equals("login")) {
String email = params[1];
String password = params[2];
try {
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("email", "UTF-8")+"="+URLEncoder.encode(email, "UTF-8")+"&"
+URLEncoder.encode("password", "UTF-8")+"="+URLEncoder.encode(password, "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String result = "";
String line = "";
while ((line = bufferedReader.readLine())!= null) {
result+= line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}

Related

I want to upload file without using multipart in spring boot, would be great if I could get you valuable suggestions on this

Shall I remove this from application.properties
spring.http.multipart.enabled=true
What should be my approach towards this file upload without using multipart?
This way, I'm able to uploading file using where I'm using multipart.
#RequestMapping(value = "/dog/create/{name}", method = RequestMethod.POST)
public JsonNode dogCreation(HttpServletRequest httpRequest, #RequestParam(value = "picture", required = false) MultipartFile multipartFile,
#PathVariable("name") String name) throws IOException, InterruptedException {
JSONObject response = new JSONObject();
Dog dog = new Dog();
String DOG_IMAGES_BASE_LOCATION = "resource\\images\\dogImages";
try {
File file = new File(DOG_IMAGES_BASE_LOCATION);
if (!file.exists()) {
file.mkdirs();
}
} catch (Exception e) {
e.printStackTrace();
}
dog = dogService.getDogByName(name);
if (dog == null) {
if (!multipartFile.isEmpty()) {
String multipartFileName = multipartFile.getOriginalFilename();
String format = multipartFileName.substring(multipartFileName.lastIndexOf("."));
try {
Path path = Paths.get(DOG_IMAGES_BASE_LOCATION + "/" + name + format);
byte[] bytes = multipartFile.getBytes();
File file = new File(path.toString());
file.createNewFile();
Files.write(path, bytes);
if (file.length() == 0) {
response = utility.createResponse(500, Keyword.ERROR, "Image upload failed");
} else {
String dbPath = path.toString().replace('\\', '/');
dog = new Dog();
dog.setName(name);
dog.setPicture(dbPath);
dog = dogService.dogCreation(dog);
response = utility.createResponse(200, Keyword.SUCCESS, "Image upload successful");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
return objectMapper.readTree(response.toString());
}
I want to do it without using multipart, what would you suggest?
This is what I've done till now to solve this
#RequestMapping(value = "/dog/create/{name}", method = RequestMethod.POST)
public JsonNode dogCreation(HttpServletRequest httpRequest, #RequestParam("picture") String picture,
#PathVariable("name") String name) throws IOException, InterruptedException {
JSONObject response = new JSONObject();
Dog dog = new Dog();
String DOG_IMAGES_BASE_LOCATION = "resource\\images\\dogImages";
try {
File file = new File(DOG_IMAGES_BASE_LOCATION);
if (!file.exists()) {
file.mkdirs();
}
} catch (Exception e) {
e.printStackTrace();
}
dog = dogService.getDogByName(name);
if (dog == null) {
if (!picture.isEmpty()) {
String dogPicture = picture;
byte[] encodedDogPicture = Base64.encodeBase64(dogPicture.getBytes());
String format = dogPicture.substring(picture.lastIndexOf("."));
try {
} catch (Exception e) {
e.printStackTrace();
}
}
}
return objectMapper.readTree(response.toString());
}
I just have to say that this should probably only be used as a workaround.
On your frontend, convert the file to base64 in js:
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(evt) {
console.log(evt.target.result);
//do POST here - something like this:
$.ajax("/upload64", {
method: "POST",
contentType: "application/text"
data: evt.target.result
}
};
On the server with an example of a decoder - more decoding options here Decode Base64 data in Java
import sun.misc.BASE64Decoder;
#PostMapping("/upload64")
public String uploadBase64(#RequestBody String payload){
BASE64Decoder decoder = new BASE64Decoder();
byte[] decodedBytes = decoder.decodeBuffer(encodedBytes);
//use your bytes
}

Https request not working for android Application

Https request not waking on my machine for an android app while HTTP is working fine.
I did lot of goggling but can't find success.
public static String requestWithPostMethod(String url, String jsonData)
* throws
* ClientProtocolException, IOException
*/
{
//HttpURLConnection urlConnection;
String result = null;
try {
// Connect
URL newurl = new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection) newurl.openConnection();
// urlConnection = createConnection(url);
urlConnection.setRequestMethod("POST");
urlConnection
.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.connect(); //here it return null exception
// Write
OutputStream outputStream = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
outputStream, "UTF-8"));
writer.write(jsonData);
writer.close();
outputStream.close();
// Read
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream(),
"UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
bufferedReader.close();
// {"success":true,"result":[],"error":"","error_key":"email_validation_code"}
result = sb.toString();
} catch (UnsupportedEncodingException e) {
if (e != null) {
e.printStackTrace();
}
} catch (IOException e) {
if (e != null) {
e.printStackTrace();
}
}
return result;
}
It might be the issue with Server Certificates.

zoho books api: list items not working - java

when I call this list Item API in zoho books:
https://www.zoho.com/invoice/api/v3/settings/items/#list-items , the response is:
{"code":4,"message":"Invalid value passed for JSONString"}
How does API work
HTTP verbs are used to access the resources - GET, POST, PUT and DELETE. All parameters in the request should be form-urlencoded. For all the APIs you need to pass authtoken and organization_id. Input JSON string should be passed using JSONString parameter.
private void testZoho() {
JSONObject JSONString = new JSONObject();
JSONString.put("sort_column", "name");
String urlParameters ="authtoken=xxxxxx&organization_id=xxxxx";
urlParameters += "&JSONString=" + JSONString.toJSONString();
System.out.println("retJson1:\n" + urlParameters);
HttpURLConnection httpcon;
String url = "https://books.zoho.com/api/v3/items";
String data = urlParameters;
String result = null;
try{
//Connect
httpcon = (HttpURLConnection) ((new URL (url).openConnection()));
httpcon.setDoOutput(true);
String charset = "UTF-8";
httpcon.setRequestProperty("Accept-Charset", charset);
httpcon.setRequestProperty("Content-Type", "application/json;charset=" + charset);
httpcon.setRequestMethod("GET");
httpcon.connect();
//Write
OutputStream os = httpcon.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(data);
writer.close();
os.close();
//Read
BufferedReader br = new BufferedReader(new InputStreamReader(httpcon.getInputStream(),"UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
result = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("retJson1:\n" + result);
}
You need to pass all parameter as url parameter instead of writing in the stream. I have modified your code:
private void testZoho()
{
HttpURLConnection httpcon;
String url = "https://books.zoho.com/api/v3/items?authtoken=xxxx&organization_id=xxx&sort_column=name";
String result = null;
try
{
//Connect
httpcon = (HttpURLConnection) ((new URL(url).openConnection()));
httpcon.setDoOutput(true);
String charset = "UTF-8";
httpcon.setRequestProperty("Accept-Charset", charset);
httpcon.setRequestProperty("Content-Type", "application/json;charset=" + charset);
httpcon.setRequestMethod("GET");
httpcon.connect();
//Read
BufferedReader br = new BufferedReader(new InputStreamReader(httpcon.getInputStream(), "UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while((line = br.readLine()) != null)
{
sb.append(line);
}
br.close();
result = sb.toString();
}
catch(UnsupportedEncodingException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
System.out.println("retJson1:\n" + result);
}

spring security - adding parameters to request for json login not working

I have been following this post on how to create an entry point into my spring mvc 3.1 web application for someone to login using a json request.
Spring Security and JSON Authentication
I've got a question about the code below. Inside attemptAuthentication I am adding extra request parameters which are json specific. And then I try to access those parameters in obtainUsername and obtainPassword but the parameters are not there.
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
if ("application/json".equals(request.getHeader("Content-Type"))) {
StringBuffer sb = new StringBuffer();
String line = null;
BufferedReader reader;
try {
reader = request.getReader();
while ((line = reader.readLine()) != null){
sb.append(line);
}
//json transformation
ObjectMapper mapper = new ObjectMapper();
JsonLoginRequest loginRequest = mapper.readValue(sb.toString(), JsonLoginRequest.class);
String jsonUsername = loginRequest.getJ_username();
request.setAttribute("jsonUsername", jsonUsername);
String jsonPassword = loginRequest.getJ_password();
request.setAttribute("jsonPassword", jsonPassword);
String jsonStore = loginRequest.getJ_store();
request.setAttribute("jsonStore", jsonStore);
}
catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
String usernameParameter = obtainUsername(request);
String password = obtainPassword(request);
When I do this jsonUsername and jsonStore don't exist even though I added them above.
#Override
protected String obtainUsername(HttpServletRequest request) {
String combinedUsername = null;
if ("application/json".equals(request.getHeader("Content-Type"))) {
String jsonUsername = request.getParameter("jsonUsername");
String jsonStore = request.getParameter("jsonStore");
combinedUsername =
jsonUsername +
SecurityConstants.TWO_FACTOR_AUTHENTICTION_DELIM +
jsonStore;
}else {
String username = super.obtainUsername(request);
String store = request.getParameter(SecurityConstants.STORE_PARAM);
String hiddenStore = request.getParameter(SecurityConstants.HIDDEN_STORE_PARAM);
combinedUsername =
username +
SecurityConstants.TWO_FACTOR_AUTHENTICTION_DELIM +
store +
SecurityConstants.TWO_FACTOR_AUTHENTICTION_DELIM +
hiddenStore;
}
return combinedUsername;
}
Can someone help me with what is wrong? thanks

Posting HTTPS form results in html 404 status code

I keep getting a HTML 404 reply from the server when I try to login via a httppost (https). Not sure if this is a cookie problem or something else. The code should be good as I have copied it from another activity. I need some help.
This is my current code:
public int postData(String usernamne, String password) {
String url = "https://domainname.com/nclogin.submit";
HttpPost httppost = new HttpPost(url);
try {
KeyStore trusted = null;
try {
trusted = KeyStore.getInstance("BKS");
} catch (KeyStoreException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
trusted.load(null, "".toCharArray());
MySSLSocketFactory sslf = null;
try {
sslf = new MySSLSocketFactory(trusted);
} catch (KeyManagementException e) {
Log.d(TAG, "Exception " + e);
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnrecoverableKeyException e) {
Log.d(TAG, "Exception " + e);
// TODO Auto-generated catch block
e.printStackTrace();
} catch (KeyStoreException e) {
Log.d(TAG, "Exception " + e);
// TODO Auto-generated catch block
e.printStackTrace();
}
sslf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("f_username", "myemail#address.com"));
nameValuePairs.add(new BasicNameValuePair("f_passwd", "mypassword"));
nameValuePairs.add(new BasicNameValuePair("f_method", "LOGIN"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("https", sslf, 443));
SingleClientConnManager cm = new SingleClientConnManager(httppost.getParams(), schemeRegistry);
// NEW API WONT ALLOW THIS IN THE MAIN THREAD! hence ASYNC
DefaultHttpClient client = new DefaultHttpClient(cm, httppost.getParams());
HttpResponse result = client.execute(httppost);
// Check if server response is valid
StatusLine status = result.getStatusLine();
Log.d(TAG, "STatus" + result.getStatusLine());
if (status.getStatusCode() != 200) {
throw new IOException("Invalid response from server: " + status.toString());
}
HttpEntity entity = result.getEntity();
InputStream is = entity.getContent();
if (is != null) {
is.close(); // release connection
}
String phpsessid = "";
// cookies from another blog
// http://stackoverflow.com/questions/4224913/android-session-management
List cookies = client.getCookieStore().getCookies();
if (cookies.isEmpty()) {
Log.d(TAG, "no cookies received");
} else {
for (int i = 0; i < cookies.size(); i++) {
// Log.d(TAG, "COOKIE-" + i + " " +
// cookies.get(i).toString());
if (cookies.get(i).toString().contains("PHPSESSID")) {
phpsessid = cookies.get(i).toString();
Log.d(TAG, "COOKIE FOR PHPSESSID - " + phpsessid);
}
}
} // end of blog
entity.consumeContent();
client.getConnectionManager().shutdown();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (CertificateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return 1;
} // end of postData()
public class MySSLSocketFactory extends SSLSocketFactory {
SSLContext sslContext = SSLContext.getInstance("TLS");
public MySSLSocketFactory(KeyStore truststore)
throws NoSuchAlgorithmException, KeyManagementException,
KeyStoreException, UnrecoverableKeyException {
super(truststore);
TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
sslContext.init(null, new TrustManager[] { tm }, null);
}
#Override
public Socket createSocket(Socket socket, String host, int port,
boolean autoClose) throws IOException, UnknownHostException {
return sslContext.getSocketFactory().createSocket(socket, host,
port, autoClose);
}
#Override
public Socket createSocket() throws IOException {
return sslContext.getSocketFactory().createSocket();
}
I know the url is correct, as are the name value pairs, as I can login via a query string via a browser or via wget:
https://domainname.com/nclogin.submit?f_username=myemail#email.com&f_passwd=password&f_method=LOGIN
This results in a connection established and a redirect to my dashboard page.
The HTML code (source) from the login page can be viewed
here

Resources