How to connect Android on external host (not localhost) - android

I decided to connect to an external host my app but don't work. How can i do?
this is an exemple:
String login_url = "http://***.**.**.**/fileman/**/register.php";
// String login_url = "http://10.0.2.2/code/register.php";
String method = params[0];
if (method.equals("register")) {
String name = params[1];
String user_name = params[2];
String user_pass = params[3];
try {
URL url = new URL(reg_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
//httpURLConnection.setDoInput(true);
OutputStream OS = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
String data = URLEncoder.encode("user", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8") + "&" +
URLEncoder.encode("user_name", "UTF-8") + "=" + URLEncoder.encode(user_name, "UTF-8") + "&" +
URLEncoder.encode("user_pass", "UTF-8") + "=" + URLEncoder.encode(user_pass, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
OS.close();
InputStream IS = httpURLConnection.getInputStream();
IS.close();
//httpURLConnection.connect();
httpURLConnection.disconnect();
ritorno = "Registration Success...";
return ritorno;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
with localhost work, but when i use my url don't work.. (if i use my url on google adress he work)
what is wrong?

Are you supposed to be using login_url rather than reg_url in URL url = new URL(reg_url)? I think reg_url was initialized with something else.

Related

How to use AsyncTask in a different process?

I'm using a Service in different process of my app using android:process=":MyService" and I recognized that my AsyncTasks in MyService class doesn't work and execute, so how can I sync my datas with my Server in MyService class?
I just want to update my Server from this class cause it's a ForegroundService that should be active most of the times. I believe that defining MyService class as a separate process helps my app's battery usage. I've already defined an inner class and used it inside MyService class but it doesn't work at all, I also tried to use another custom asyncTask class Object in MyService class but it doesn't work either
here's an example of my code in MyService class:
static class UpdatePoint extends AsyncTask<String,String,String>{
#Override
protected String doInBackground(String... strings) {
String userId = user.get(SessionManager.getKeyId()).toString();
String coin = strings[1];
String step = strings[2];
String log_lat = strings[3];
String log_lng = strings[4];
String log_zone = strings[5];
String log_address = strings[6];
//Log.d("updatePoint","coin:"+coin+", step:"+step);
try {
String update_point_url = "http://mohregroup.ir/db-mapapa/updatePoint.php";
URL url = new URL(update_point_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(5*1000);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String data = URLEncoder.encode("userId", "UTF-8") + "=" + URLEncoder.encode(userId, "UTF-8")
+ "&" + URLEncoder.encode("coin", "UTF-8") + "=" + URLEncoder.encode(coin, "UTF-8")
+ "&" + URLEncoder.encode("step", "UTF-8") + "=" + URLEncoder.encode(step, "UTF-8")
+ "&" + URLEncoder.encode("log_lat", "UTF-8") + "=" + URLEncoder.encode(log_lat, "UTF-8")
+ "&" + URLEncoder.encode("log_lng", "UTF-8") + "=" + URLEncoder.encode(log_lng, "UTF-8")
+ "&" + URLEncoder.encode("log_zone", "UTF-8") + "=" + URLEncoder.encode(log_zone, "UTF-8")
+ "&" + URLEncoder.encode("log_address", "UTF-8") + "=" + URLEncoder.encode(log_address, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
StringBuilder response = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
response.append(line);
}
//Log.d("updatePoints response:", response.toString().trim());
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
Timber.d("done Successfully!");
return response.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
and using it inside another method of MyService class :
if (getAddress() != null) {
if (getAddress().getFeatureName() == null &&
getAddress().getAddressLine(0) != null) {
new UpdatePoint().execute(String.valueOf(coins),
String.valueOf(steps),
String.valueOf(originLocation.getLatitude()),
String.valueOf(originLocation.getLongitude()),
getAddress().getFeatureName(), "not titled");
} else if (getAddress().getFeatureName() != null &&
getAddress().getAddressLine(0) == null) {
new UpdatePoint().execute(String.valueOf(coins),
String.valueOf(steps),
String.valueOf(originLocation.getLatitude()),
String.valueOf(originLocation.getLongitude()),
"not titled", getAddress().getAddressLine(0));
} else {
new UpdatePoint().execute(String.valueOf(coins), String.valueOf(steps),
String.valueOf(originLocation.getLatitude()), String.valueOf(originLocation.getLongitude()),
getAddress().getFeatureName(), getAddress().getAddressLine(0));
}
} else {
new UpdatePoint().execute(String.valueOf(coins), String.valueOf(steps),
String.valueOf(originLocation.getLatitude()), String.valueOf(originLocation.getLongitude()),
"not titled", "not titled");
}
So, any Ideas about
how to use an asyncTask in a service with different process?
or
any other way in order to update the server from a service with different process?
any helps would be appreciated a lot!
Thanks.
One way could be using timer and when timer is finished you can call asynctask and reset the timer again.

Add header to post request in string

I'm using that code to send POST requests.
Now i need to add header to this, any ways of doing it?
In Google most ways is to use another methods, like HttpPost and addHeader method.
try {
System.out.println("FirebaseInstanceId.getInstance().getToken()" + token);
//String data = URLEncoder.encode("?api-fcm=register", "UTF-8");
String data = URLEncoder.encode("regid", "UTF-8")
+ "=" + URLEncoder.encode(FirebaseInstanceId.getInstance().getToken(), "UTF-8");
if ( ContextCompat.checkSelfPermission( this, Manifest.permission.READ_PHONE_STATE ) == PackageManager.PERMISSION_GRANTED ) {
data += "&" + URLEncoder.encode("serial", "UTF-8") + "=" + URLEncoder.encode( Build.SERIAL, "UTF-8");
}
data += "&" + URLEncoder.encode("device_name", "UTF-8")
+ "=" + URLEncoder.encode(getDeviceName(), "UTF-8");
data += "&" + URLEncoder.encode("os_version", "UTF-8")
+ "=" + URLEncoder.encode(getAndroidVersion(), "UTF-8");
String text = "";
BufferedReader reader = null;
try {
URL url = new URL("http://somelink");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
text = sb.toString();
} catch (Exception ex) {
Do code like this:
HttpUrlConnection myURLConnection = (HttpUrlConnection)conn;
myURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
myURLConnection.setRequestProperty("Content-Length", "" + postData.getBytes().length);
myURLConnection.setRequestProperty("Content-Language", "en-US");
add this after line:
URLConnection conn = url.openConnection();
and here "Content-Type", "Content-Length", "Content-Language" are headers here.
Thanks and let me know if need more.
happy Coding!!

do in background split not working

please i want to know what is wrong with this code, if i try to split, it just crashes my app, but without the split line of code my app runs sucessfully and returns a response from my server with the delimeter "|" here is the code:
protected String doInBackground(String... params) {
String type= params[0];
String login_url="somelink.com/somelink.php";
if(type.equals("login")){
try {
String username= params[1];
String password= params[2];
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 data=URLEncoder.encode("n", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8");
data+="&" + URLEncoder.encode("p", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
bufferedWriter.write(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;
}
String[] words=result.split("\\|");
StringBuilder ch=new StringBuilder();
ch.append(words[0]);
String check=ch.toString();
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return check;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
The only obvious thing I can see is that you are probably accessing an element that does not exist. This line:
ch.append(words[0]);
It's possible that the length of the words array, in some cases, can be zero (e.g., because line is empty, etc.), and you are trying to access a non-existent element.
All you have to do is add if statement to check if you have a non-empty array before you do words[0].

Android HttpURLConnection image uploads but file not recognized as JPEG

I have this code which is able to upload a JPEG file to the server but the file is not recognized as JPEG. I think my problem is about encoding the JPEG file correctly. My solution is essentially the same as this one. I have tried other variants in appending the JPEG bytes using FileInputStream and using DataOutputStream instead of OutputStreamWriter, etc to no avail. Any suggestion appreciated.
final String boundary = "==================";
final String mimeType = "image/jpeg";
final int IMAGE_QUALITY = 100;
URL url = null;
HttpURLConnection urlConnection = null;
OutputStreamWriter request = null;
String response = null;
try {
url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true); ///
urlConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
urlConnection.setRequestMethod("POST");
OutputStream outputStream= urlConnection.getOutputStream();
request = new OutputStreamWriter(outputStream);
request.append("--" + boundary).append("\n");
request.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + imageFileName + "\"").append("\n\n");
request.append("Content-Type: " + mimeType).append("\n\n");
request.append("Content-Encoding: base64").append("\n\n");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
imageThumbnail.compress(Bitmap.CompressFormat.JPEG, IMAGE_QUALITY, stream);
byte[] byteArray = stream.toByteArray();
//request.append(new String(byteArray)).append("\n");
String encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
request.append(encodedImage);
request.append("--" + boundary + "--");
request.flush();
request.close();
String line = null;
InputStreamReader isr = new InputStreamReader(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
response = sb.toString(); // = "Success"
isr.close();
reader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
response = "Malformed URL";
} catch (IOException e) {
e.printStackTrace();
response = "IO Exception";
}
return response;
Thanks to this post here, solution is as follows:
final String boundary = "==================";
final String twoHyphens = "--";
final String crlf = "\r\n";
final String mimeType = "image/jpeg";
final int IMAGE_QUALITY = 100;
URL url = null;
HttpURLConnection urlConnection = null;
DataOutputStream dos;
String response = null;
try {
url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true); ///
urlConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
//urlConnection.setRequestProperty("Content-Type", "image/jpeg");
urlConnection.setRequestMethod("POST");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
imageThumbnail.compress(Bitmap.CompressFormat.JPEG, IMAGE_QUALITY, stream);
byte[] byteArray = stream.toByteArray();
dos = new DataOutputStream(urlConnection.getOutputStream());
dos.writeBytes(twoHyphens + boundary + crlf);
dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + imageFileName + "\"" + crlf);
dos.writeBytes("Content-Type: " + mimeType + crlf);
dos.writeBytes(crlf);
dos.write(byteArray);
dos.writeBytes(crlf);
dos.writeBytes(twoHyphens + boundary + twoHyphens);
dos.flush();
dos.close();
String line = null;
InputStreamReader isr = new InputStreamReader(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
response = sb.toString();
isr.close();
reader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
response = "Malformed URL";
} catch (IOException e) {
e.printStackTrace();
response = "IO Exception";
}
return response;
I have these inside the #Override protected String doInBackground(String... params) of an AsyncTask<String, Void, String>

Sinch - Message Api not working

Always getting the Bad Request error, error code - 400. Using commons-codec-1.10 jar file but its not available for native Android. here is my code
Date date = new java.util.Date();
DateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss'Z'");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String timestamp = dateFormat.format(date);
String httpVerb = "POST";
String path = "/v1/sms/" + "+918003059919";
String contentType = "application/json";
String canonicalizedHeaders = "x-timestamp:" + timestamp;
String body = "{\"message\":\"" + "Hiiii" + "\"}";
byte[] data = md5Digest(body);
String contentMd5 = Base64.encodeToString(data, 0, data.length,
Base64.DEFAULT);
String stringToSign = httpVerb + "\n" + contentMd5 + "\n"
+ contentType + "\n" + canonicalizedHeaders + "\n"
+ path;
String signature = signature(SinchService.APP_SECRET,
stringToSign);
String authorization = "Application " + SinchService.APP_KEY
+ ":" + signature;
URL url = new URL("https://messagingApi.sinch.com" + path);
HttpsURLConnection connection = (HttpsURLConnection) url
.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("content-type",
"application/json");
connection.setRequestProperty("x-timestamp", timestamp);
connection.setRequestProperty("authorization", Base64.encodeToString(authorization.getBytes(),Base64.DEFAULT));
OutputStream os = connection.getOutputStream();
os.write(body.getBytes());
StringBuilder response = new StringBuilder();
int status = connection.getResponseCode();
System.out.println("resonse code: "+status);
InputStream iresponse = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = br.readLine()) != null)
response.append(line);
br.close();
os.close();
Using android.util.Base64 package to encode but not its not working.
Sinch applications are not automatically whitelisted for sending SMS. Contact them at dev#sinch.com to get your app whitelisted.

Categories

Resources