Http Get using Android HttpURLConnection - java

I'm new to Java and Android development and try to create a simple app which should contact a web server and add some data to a database using a http get.
When I do the call using the web browser in my computer it works just fine. However, when I do the call running the app in the Android emulator no data is added.
I have added Internet permission to the app's manifest. Logcat does not report any problems.
Can anyone help me to figure out what's wrong?
Here is the source code:
package com.example.httptest;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class HttpTestActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
setContentView(tv);
try {
URL url = new URL("http://www.mysite.se/index.asp?data=99");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.disconnect();
tv.setText("Hello!");
}
catch (MalformedURLException ex) {
Log.e("httptest",Log.getStackTraceString(ex));
}
catch (IOException ex) {
Log.e("httptest",Log.getStackTraceString(ex));
}
}
}

Try getting the input stream from this you can then get the text data as so:-
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL("http://www.mysite.se/index.asp?data=99");
urlConnection = (HttpURLConnection) url
.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
char current = (char) data;
data = isw.read();
System.out.print(current);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
You can probably use other inputstream readers such as buffered reader also.
The problem is that when you open the connection - it does not 'pull' any data.

Here is a complete AsyncTask class
public class GetMethodDemo extends AsyncTask<String , Void ,String> {
String server_response;
#Override
protected String doInBackground(String... strings) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
server_response = readStream(urlConnection.getInputStream());
Log.v("CatalogClient", server_response);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.e("Response", "" + server_response);
}
}
// Converting InputStream to String
private String readStream(InputStream in) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
}
To Call this AsyncTask class
new GetMethodDemo().execute("your web-service url");

I have created with callBack(delegate) response to Activity class.
public class WebService extends AsyncTask<String, Void, String> {
private Context mContext;
private OnTaskDoneListener onTaskDoneListener;
private String urlStr = "";
public WebService(Context context, String url, OnTaskDoneListener onTaskDoneListener) {
this.mContext = context;
this.urlStr = url;
this.onTaskDoneListener = onTaskDoneListener;
}
#Override
protected String doInBackground(String... params) {
try {
URL mUrl = new URL(urlStr);
HttpURLConnection httpConnection = (HttpURLConnection) mUrl.openConnection();
httpConnection.setRequestMethod("GET");
httpConnection.setRequestProperty("Content-length", "0");
httpConnection.setUseCaches(false);
httpConnection.setAllowUserInteraction(false);
httpConnection.setConnectTimeout(100000);
httpConnection.setReadTimeout(100000);
httpConnection.connect();
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
return sb.toString();
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (onTaskDoneListener != null && s != null) {
onTaskDoneListener.onTaskDone(s);
} else
onTaskDoneListener.onError();
}
}
where
public interface OnTaskDoneListener {
void onTaskDone(String responseData);
void onError();
}
You can modify according to your needs. It's for get

If you just need a very simple call, you can use URL directly:
import java.net.URL;
new URL("http://wheredatapp.com").openStream();

Simple and Efficient Solution : use Volley
StringRequest stringRequest = new StringRequest(Request.Method.GET, finalUrl ,
new Response.Listener<String>() {
#Override
public void onResponse(String){
try {
JSONObject jsonObject = new JSONObject(response);
HashMap<String, Object> responseHashMap = new HashMap<>(Utility.toMap(jsonObject)) ;
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("api", error.getMessage().toString());
}
});
RequestQueue queue = Volley.newRequestQueue(context) ;
queue.add(stringRequest) ;

A more contemporary way of doing it on a separate thread using Tasks and Kotlin
private val mExecutor: Executor = Executors.newSingleThreadExecutor()
private fun createHttpTask(u:String): Task<String> {
return Tasks.call(mExecutor, Callable<String>{
val url = URL(u)
val conn: HttpURLConnection = url.openConnection() as HttpURLConnection
conn.requestMethod = "GET"
conn.connectTimeout = 3000
conn.readTimeout = 3000
val rc = conn.responseCode
if ( rc != HttpURLConnection.HTTP_OK) {
throw java.lang.Exception("Error: ${rc}")
}
val inp: InputStream = BufferedInputStream(conn.inputStream)
val resp: String = inp.bufferedReader(UTF_8).use{ it.readText() }
return#Callable resp
})
}
and now you can use it like below in many places:
createHttpTask("https://google.com")
.addOnSuccessListener {
Log.d("HTTP", "Response: ${it}") // 'it' is a response string here
}
.addOnFailureListener {
Log.d("HTTP", "Error: ${it.message}") // 'it' is an Exception object here
}

URL url = new URL("https://www.google.com");
//if you are using
URLConnection conn =url.openConnection();
//change it to
HttpURLConnection conn =(HttpURLConnection )url.openConnection();

Related

How to create library for GCM, library creation does not work

I'm trying to create a library for my apps, in all my apps have push notification.
I would like to take this package and create a library
In GCM do I have any limitations? Because it looks like it gets the package name to generate ID_TOKEN
I have an APP that has a package with the classes I use for PUSH notification, it works perfectly!
Now I've migrated this package and created a library, because so all other apps are just pointing the lib and it will be working.
Only that for some reason he does not call the lib, I've done everything and I can not.
The code to register the ID in GCM and start the service is this below:
Intent intent = new Intent(this, RegistrationIntentService.class);
startService(intent);
This code above is in my MainActivity
I thought that by doing so he would already call the library
EDIT:
I am using Eclipse and GCM
My class `RegistrationIntentService`
public class RegistrationIntentService extends IntentService {
private static final String TAG = "RegServicePush";
String newRegID = "";
String GetEmail = "";
public RegistrationIntentService() {
super(TAG);
}
#Override
protected void onHandleIntent(Intent intent) {
try {
InstanceID instanceID = InstanceID.getInstance(this);
String token = instanceID.getToken(Constants.GCM_SENDER_ID, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
// TODO: Implement this method to send any registration to your
// app's servers.
sendRegistrationToServer(token, email);
} catch (Exception e) {
Log.d(TAG, "Failed to complete token refresh", e);
}
// Notify UI that registration has completed, so the progress indicator
// can be hidden.
}
private void sendRegistrationToServer(String token, String email) {
//MainActivity.newRegID = token;
WebServerRegistrationTask webServer = new WebServerRegistrationTask();
webServer.execute();
}
public class WebServerRegistrationTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(RegistrationIntentService.this);
URL url = null;
try {
url = new URL(Constants.WEB_SERVER_URL);
} catch (MalformedURLException e) {
e.printStackTrace();
sharedPreferences.edit().putString(Constants.PREF_GCM_REG_ID, "").apply();
}
Map<String, String> dataMap = new HashMap<String, String>();
dataMap.put("regID", newRegID);
dataMap.put("appID", Constants.APP_ID);
StringBuilder postBody = new StringBuilder();
Iterator<Map.Entry<String, String>> iterator = dataMap.entrySet().iterator();
while (iterator.hasNext()) {
Entry<String, String> param = (Entry<String, String>) iterator.next();
postBody.append(param.getKey()).append('=').append(param.getValue());
if (iterator.hasNext()) {
postBody.append('&');
}
}
String body = postBody.toString();
byte[] bytes = body.getBytes();
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
OutputStream out = conn.getOutputStream();
out.write(bytes);
out.close();
String response = "";
InputStream is = null;
try {
is = conn.getInputStream();
int ch;
StringBuffer sb = new StringBuffer();
while ((ch = is.read()) != -1) {
sb.append((char) ch);
}
response = sb.toString();
} catch (IOException e) {
throw e;
} finally {
if (is != null) {
is.close();
}
}
int status = conn.getResponseCode();
if (status == 200) {
if (response.equals("1")) {
sharedPreferences.edit().putString(Constants.PREF_GCM_REG_ID, newRegID).apply();
Intent registrationComplete = new Intent(Constants.SERVER_SUCCESS);
LocalBroadcastManager.getInstance(RegistrationIntentService.this)
.sendBroadcast(registrationComplete);
}
} else {
throw new IOException("Request failed with error code " + status);
}
} catch (ProtocolException pe) {
pe.printStackTrace();
sharedPreferences.edit().putString(Constants.PREF_GCM_REG_ID, "").apply();
} catch (IOException io) {
io.printStackTrace();
sharedPreferences.edit().putString(Constants.PREF_GCM_REG_ID, "").apply();
} finally {
if (conn != null) {
conn.disconnect();
}
}
return null;
}
}
}

How can i connect to my MySQL database with an android app?

i am trying to do an android app to write some datas on MySQL database but it does not work i did a Java class for this and i think the problem comes from this. Here is my code :
public class BackgroundTask extends AsyncTask<String, Void, String> {
Context ctx;
BackgroundTask(Context ctx) {this.ctx = ctx;}
#Override
protected String doInBackground(String... params) {
String reg_url = "http://localhost:8080/project/register.php";
String method = params[0];
if (method.equals("register")) {
String name = params[1];
String password = params[2];
String contact = params[3];
String country = params[4];
try {
URL url = new URL(reg_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream os = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
String data = URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8") + "&" +
URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8") + "&" +
URLEncoder.encode("contact", "UTF-8") + "=" + URLEncoder.encode(contact, "UTF-8") + "&" +
URLEncoder.encode("country", "UTF-8") + "=" + URLEncoder.encode(country, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
os.close();
InputStream IS = httpURLConnection.getInputStream();
IS.close();
return "Registration success";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
Actually what i would like is to save name, password, contact and country in my database. The problem is this : "Registration success" is never returned it is always null. But i don't know why. When i try to compile it looks like there is no errors and i can see the app.
Thank you very much for your help !
Edit : This is the register.php :
<?php
require "init.php";
$u_name=$_POST["name"];
$u_password=$_POST["password"];
$u_contact=$_POST["contact"]";
$u_country=$_POST["country"];
$sql_query="insert into users values('$u_name', '$u_password', '$u_contact', '$u_country');";
//mysqli_query($connection, $sql_query));
if(mysqli_query($connection,$sql_query))
{
//echo "data inserted";
}
else{
//echo "error";
}
?>
And also the init.php :
<?php
$db_name = "project";
$mysql_user = "root";
$server_name = "localhost";
$connection = mysqli_connect($server_name, $mysql_user, "", $db_name);
if(!$connection){
echo "Connection not successful";
}
else{
echo "Connection successful";
}
?>
Thank you for your help !
My class PutUtility for getData(), PostData, DeleteData(). you just need to change package name
package fourever.amaze.mics;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class PutUtility {
private Map<String, String> params = new HashMap<>();
private static HttpURLConnection httpConnection;
private static BufferedReader reader;
private static String Content;
private StringBuffer sb1;
private StringBuffer response;
public void setParams(Map<String, String> params) {
this.params = params;
}
public void setParam(String key, String value) {
params.put(key, value);
}
public String getData(String Url) {
StringBuilder sb = new StringBuilder();
try {
// Defined URL where to send data
URL url = new URL(Url);
URLConnection conn = null;
conn = url.openConnection();
// Send POST data request
httpConnection = (HttpURLConnection) conn;
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConnection.setRequestMethod("GET");
BufferedReader in = new BufferedReader(
new InputStreamReader(httpConnection.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception ex) { }
}
return response.toString();
}
public String postData(String Url) {
StringBuilder sb = new StringBuilder();
for (String key : params.keySet()) {
String value = null;
value = params.get(key);
if (sb.length() > 0) {
sb.append("&");
}
sb.append(key + "=" + value);
}
try {
// Defined URL where to send data
URL url = new URL(Url);
URLConnection conn = null;
conn = url.openConnection();
// Send POST data request
httpConnection = (HttpURLConnection) conn;
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConnection.setRequestMethod("POST");
httpConnection.setDoInput(true);
httpConnection.setDoOutput(true);
OutputStreamWriter wr = null;
wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(sb.toString());
wr.flush();
BufferedReader in = new BufferedReader(
new InputStreamReader(httpConnection.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception ex) {
}
}
return response.toString();
}
public String putData(String Url) {
StringBuilder sb = new StringBuilder();
for (String key : params.keySet()) {
String value = null;
try {
value = URLEncoder.encode(params.get(key), "UTF-8");
if (value.contains("+"))
value = value.replace("+", "%20");
//return sb.toString();
// Get the server response
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (sb.length() > 0) {
sb.append("&");
}
sb.append(key + "=" + value);
}
try {
// Defined URL where to send data
URL url = new URL(Url);
URLConnection conn = null;
conn = url.openConnection();
// Send PUT data request
httpConnection = (HttpURLConnection) conn;
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConnection.setRequestMethod("PUT");
httpConnection.setDoInput(true);
httpConnection.setDoOutput(false);
OutputStreamWriter wr = null;
wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(sb.toString());
wr.flush();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
;
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
// Append server response in string
sb1.append(line + " ");
}
// Append Server Response To Content String
Content = sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception ex) {
}
}
// Send PUT data request
return Url;
}
public String deleteData(String Url) {
StringBuilder sb = new StringBuilder();
for (String key : params.keySet()) {
try {
// Defined URL where to send data
URL url = new URL(Url);
URLConnection conn = null;
conn = url.openConnection();
// Send POST data request
httpConnection = (HttpURLConnection) conn;
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConnection.setRequestMethod("DELETE");
httpConnection.connect();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
// Append server response in string
sb1.append(line + " ");
}
// Append Server Response To Content String
Content = sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception ex) {
}
}
}
return Url;
}
}
And use this class like this
#Override
protected String doInBackground(String... params) {
res = null;
PutUtility put = new PutUtility();
put.setParam("ueid", params[0]);
put.setParam("firm_no", params[1]);
put.setParam("date_incorporation", params[2]);
put.setParam("business_name", params[3]);
put.setParam("block_no", params[4]);
try {
res = put.postData(
"Api URL here");
Log.v("res", res);
} catch (Exception objEx) {
objEx.printStackTrace();
}
return res;
}
#Override
protected void onPostExecute(String res) {
try {
} catch (Exception objEx) {
mProgressDialog.dismiss();
objEx.printStackTrace();
}
}
Please use this. Hope it helps you in future also.
Check this if this is the problem
$u_contact=$_POST["contact"]"
here is the problem i think so brother. replace with
$u_contact=$_POST["contact"];

POST data not sent via HttpURLConnection

I'm trying to send POST request via HttpURLConnection, here is the code
public class BackgroundTask extends AsyncTask<String, Void, Void> {
Context context;
Activity activity;
StringBuffer str = null;
int responseCode;
String responseMessage;
public BackgroundTask(Context context) {
this.context = context;
this.activity = (Activity) context;
}
#Override
protected Void doInBackground(String... params) {
HttpURLConnection connection = null;
OutputStream outputStream = null;
InputStream inputStream = null;
BufferedReader reader = null;
BufferedWriter writer = null;
String method = params[1];
if(method.equals("post")) {
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
outputStream = connection.getOutputStream();
writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String data = URLEncoder.encode(params[2] + "=" + params[3], "UTF-8");
writer.write(data);
responseCode = connection.getResponseCode();
responseMessage = connection.getResponseMessage();
inputStream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream));
str = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
str.append(line);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (writer != null) {
try {
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} else if(method.equals("get")) {
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Void aVoid) {
TextView txt = (TextView) activity.findViewById(R.id.txt);
if(str != null)
txt.setText(str.toString());
Toast.makeText(activity, responseMessage, Toast.LENGTH_LONG).show();
}
}
responseCode is 200 which means everything went OK, however it says Undefined index: id
id is well defined inside php file
$user = User::find_by_id($_POST['id']);
echo json_encode($user);
and it works fine when I send post request from an html file yet when i send it from application it says id undefined which means that POST data is not sent.
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BackgroundTask myTask = new BackgroundTask(MainActivity.this);
myTask.execute(link, "post", "id", "5");
}
});
this is how i instantiate asynctask object inside main activity
UPDATE: when i send not encoded string it works fine!
writer.write("id=5"); // works perfectly!
what is wrong with URLEncoder i use in the code?
I believe you have a problem in this line:
String data = URLEncoder.encode(params[2] + "=" + params[3], "UTF-8");
You are url-encoding the = as well as the params, that's why the server cannot recognise the form fields. Try to encode the params only:
String data = URLEncoder.encode(params[2], "UTF-8") + "=" + URLEncoder.encode(params[3], "UTF-8");
The reason is that URL encoding is for passing special characters like = in the value(or key). Basically, the server will split and parse the key-value pairs with & and = before doing the decoding. And when you url-encode the = character, the server simply couldn't recognise it during the split and parse phase.
When i need to communicate with the server i use this
Server Class
public static String sendPostRequest(String requestURL,
HashMap<String, String> postDataParams) {
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
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()));
response = br.readLine();
} else {
response = "Error Registering";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
private static 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();
}
OtherClass
//Run this inside an Asynctask
HashMap<String,String> data = new HashMap<>();
data.put("id", id);
String serverResponce = Server.sendPostRequest(URL,data);

What is the proper way of Exception Handling in the following scenario:

I have an Async task which checks for user session. This task is responsible for contacting the server using a method - both are listed below:
public class SessionChecker extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Intent intent;
if (result.equalsIgnoreCase("exception")) {
//We got an exception in URL Connection - letus restart the task -- this is recursive
new SessionChecker().execute();
} else if (result.equalsIgnoreCase("server error")) {
//We got an exception in URL Connection - letus restart the task -- this is recursive
new SessionChecker().execute();
} else {
try {
JSONObject jObj = new JSONObject(result);
if (!TextUtils.isEmpty(result)) {
String message = jObj.getString("message");
if (message.equalsIgnoreCase("failure")) {
intent = new Intent(AppInitializer.this, AppWebViewLogin.class);
startActivity(intent);
} else if (message.equalsIgnoreCase("success")) {
intent = new Intent(AppInitializer.this, NavigationMasterActivity.class);
startActivity(intent);
}
}
} catch (JSONException ex) {
//Malformed JSON - letus restart the task -- this is recursive
new SessionChecker().execute();
}
}
}
#Override
protected String doInBackground(Void... params) {
DomainManager domainManager = new DomainManager(AppInitializer.this);
return UniversalNetworkConnection.simplePost(domainManager.getDomain() + getResources().getString(R.string.url_check_session));
}
}
Here is my URL Connection method:
public static String simplePost(String myurl) {
HttpsURLConnection conn = null;
try {
SSLContext sslcontext = SSLContext.getInstance("TLSv1");
sslcontext.init(null, null, null);
SSLSocketFactory NoSSLv3Factory = new NoSSLv3SocketFactory(sslcontext.getSocketFactory());
HttpsURLConnection.setDefaultSSLSocketFactory(NoSSLv3Factory);
StringBuffer response;
URL url = new URL(myurl);
conn = (HttpsURLConnection) url.openConnection();
// conn.setReadTimeout(90000);
// conn.setConnectTimeout(900000);
conn.setRequestProperty("Content-Type", "application/json");
CookieManager cookieManager = CookieManager.getInstance();
String cookie = cookieManager.getCookie(new URL(myurl).getHost());
conn.setDoOutput(true);
conn.setRequestProperty("Cookie", cookie);
conn.setRequestMethod("POST");
int responseCode = conn.getResponseCode();
switch (responseCode) {
case 200:
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
default:
return "server error";
}
} catch (IOException | java.security.KeyManagementException | java.security.NoSuchAlgorithmException ex) {
ex.printStackTrace();
return "exception";
} finally {
if (conn != null) {
try {
conn.disconnect();
} catch (Exception ex) {
ex.printStackTrace();
return "exception";
}
}
}
}
I have tried handling the exceptions recursively - an exception occurs - The async task is reloaded, how can I improve this, I am not sure if the way I am doing this is the best practice? Any hints / solutions / tips would be really helpful.

How to call JSP page in Android

I'm implementing JSP page in my Android application. I don't know how to use JSP Url in Android. I tried and run the application. But the page is blank does not show any info in Android layout and also in log cat. Here is my code.
public class JSP_Activity extends Activity
{
public static String strUrl=null;
String strText = null;
public void OnCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.jsp_page);
connectWithGet_JspPage();
}
private void connectWithGet_JspPage()
{
class GetJspPage extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... strUrls)
{
// TODO Auto-generated method stub
strUrl="http://test.window2india.com/mobile/home.jsp";
Log.e("strUrl :=","" + strUrl);
String strOutPut = null;
strOutPut=getOutPutFromUrl(strUrl);
Log.e("strOutPut :="," "+strOutPut);
return strOutPut.toString();
}
protected void onPostExecute(String output1)
{
//outputText.setText(output1);
Log.e("strOutPut :="," "+output1);
}
}
GetJspPage getJspPageAsyncTask = new GetJspPage();
getJspPageAsyncTask.execute();
}
private String getOutPutFromUrl(String url)
{
StringBuffer output = new StringBuffer("");
try
{
InputStream stream = getHttpConnection(url);
BufferedReader buffer = new BufferedReader(new InputStreamReader(stream));
String s = "";
while ((s = buffer.readLine()) != null)
output.append(s);
}
catch (IOException e1)
{
e1.printStackTrace();
}
return output.toString();
}
private InputStream getHttpConnection(String urlString)
throws IOException
{
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try
{
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK)
{
stream = httpConnection.getInputStream();
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
return stream;
}
}
Try this code,it will help for display the content send by the jsp.This code is useful for normal layout not for webview.You have to parse the content and display in your custom layout.
new Thread(new Runnable()
{
public void run()
{
try
{
URL url = new URL("http://test.window2india.com/mobile/home.jsp");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader r = new BufferedReader(new InputStreamReader(in));
String x = "";
String total = "";
int i=0;
ArrayList<String> content = new ArrayList();
while((x = r.readLine()) != null)
{
content.add(x);
}
in.close();
r.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}).start();

Categories

Resources