Not able to send simple GET Http request - android

I included following permissions into Manifest:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
I am using this code:
try {
java.net.URL url = new URL("http://www.temp372.000webhostapp.com/s.php?t=hello_there");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
t1.setText("problem occured..");
}
Following is the PHP code:
<?php
$fn = "android.txt";
$data = "";
// get whatever they send and store it to the file.
if($_GET["t"])
{
$data = $_GET["t"];
if ($data !== '')
{
$myfile = fopen($fn, "a");
fwrite($myfile, $data . "\n");
fclose($myfile);
}
}
?>
No errors are coming, I am trying running this app into bluestacks and my cellphone (ROG Phone).
But results are same, no error or anything as textview is not setting and it just my PHP code is not receiving the information but when I try same URL into my web browser, PHP code runs cool.

HTTP or "clear text" forbidden on default, you should allow it inside < application > in AndroidManifest.xml android:usesCleartextTraffic="true"

It worked well following are things I got:
I don't have to add the following into manifest:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
I also didn't have to add any permission like android:usesCleartextTraffic="true" OR any network_security_config.xml in Manifest.
It worked when I ran the code into AsyncTask in Background thread like followings:
AsyncTask.execute(new Runnable() {
#Override
public void run() {
HttpClient httpclient = new DefaultHttpClient();
try {
httpclient.execute(new HttpGet("https://temp372.000webhostapp.com/s_get.php?t=MyWorld"));
} catch (IOException e) {
e.printStackTrace();
}
}
});
I thanks Artem for this and everyone else who were trying their best.

Related

Android app hangs on HttpUrlConnection request

I created a small demo program
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
(new Requester()).execute();
}
static class Requester extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... voids) {
URL loginURL;
HttpURLConnection urlConnection;
try {
loginURL = new URL("https://google.com");
urlConnection = (HttpURLConnection) loginURL.openConnection();
int responseCode = urlConnection.getResponseCode();
Log.d("response", "response is" + responseCode);
}
catch (MalformedURLException e){
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}
return null;
}
}
}
I set a breakpoint at int responseCode = urlConnection.getResponseCode(); and then step through. It never gets to the next line for me to read the response code. There is no error; it just hangs forever.
I feel like this is the most basic urlconnection code I can come up with. Perhaps I'm missing something important.
Edit: I have indeed added the internet permission to my manifest. Here is my entire manifest just in case you want it:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.testingcorruptbitmap">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Update:
I've edited my code to include reading from the request.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
(new Requester()).execute();
}
static class Requester extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... voids) {
URL loginURL;
HttpURLConnection urlConnection;
try {
loginURL = new URL("https://google.com");
urlConnection = (HttpURLConnection) loginURL.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = reader.readLine();
Log.d("urlconnection", "line is " + line);
int responseCode = urlConnection.getResponseCode();
Log.d("urlconnection", "response is " + responseCode);
}
catch (MalformedURLException e){
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}
catch (Exception e){
e.printStackTrace();
}
return null;
}
}
}
When I set a breakpoint at the beginning of the code and walkthrough, it freezes at InputStream in = new BufferedInputStream(urlConnection.getInputStream());
So this does not solve the issue.
Solution update:
Something was wrong with the android emulated device I was working on. I restarted it and the problem is now fixed. If you know of the reason why this would happen please let me and the rest of the internet know, so we can avoid it!
You are not doing an actual request, so there is no response either, that's why your code is waiting for a response.
See here: Http Get using Android HttpURLConnection
have you added the INTERNET permission in your AndroidManifest? If not do so.
If you did take a look at this document by android-dev. It shows how to make simple requests using the volley library.
Hope this helps
Edit:
I personally never worked with URLConnection but according to the android docs you have to do it like this:
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
} finally {
urlConnection.disconnect();
}
Source: https://developer.android.com/reference/java/net/HttpURLConnection
In your example you just created a HttpURLConnection but never executed it and thats why you can'T get something of it.
While it can definitly work this this method I would greatly encurage you to take a look at Volley as it is more simple and easier to use. It also helps you with JSONRequests. Furthermore it is async by default meaning you don't need to use the deprecated AsyncTask anymore.
Edit 2:
When trying to connect to a secure website over https as you try to do in your example you need to cast to HttpsURLConnection instead.
I also have the same problem, the call to the getResponseCode method freezes. If I set a timeout, the timeout expired exception is thrown.
But all of the above happens when I have the phone in power saving mode, if I remove it, the call to the getResponseCode method works perfectly.
If the Volley api is used, a timeout also occurs.
But this only happens in background processes for example when updating a widget due to restrictions imposed by the system.
The solution is to add your app to the list of energy saving exclusions. Although this can be done through the PowerManager api, it is preferable that it be the user of your app who does it, as discussed in this answer https://stackoverflow.com/a/53115804/1735246.

Android send HTTP PUT, but error: isDataScedulerEnabled():False

I'm trying to send a PUT request but failing bad in it.
Only the first time I'm trying to send data the following line follows up in the log (in further use no exceptions are thrown):
E/DataScheduler: isDataSchedulerEnabled():false
I tried to google out what could that possibly mean, but with no luck. And even that in the further attempts on sending data the mentioned exception wont raise anymore, still no data is being sent. I'm trying to send it on my own server and I can see no connections are received on that side. Using my Android's browser I can send a successful GET request however.
I've also set the permission for Internet already by:
<uses-permission android:name="android.permission.INTERNET" />
I'm not very familiar with Java or Android but as far as I know the request should be formed and sent the following way:
public void sendFilesWithPut(String address, String file) {
new AsyncTask<String,Void,Void>() {
#Override
protected Void doInBackground(String... params) {
try {
//Log.d("HTTP:","Address:"+params[0]+":"+params[1]+" file:"+params[2]);
URL url = new URL("http://" + params[0] + ":" + params[1]);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("PUT");
OutputStreamWriter out = new OutputStreamWriter(httpCon.getOutputStream());
out.write(params[2]);
out.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}.execute(address, Integer.toString(port), file);
}
I can print a line to Log every time I attempt to send a PUT request and it's all correct: IP, port and the to-be-sent-String.
Any ideas how to make it work?
I suspect that params[0] and params[1] are actually the address and port for your url. If so then you may wish to refer to the following post:
Making PUT request with JSON data using HttpURLConnection is not working
Where the content will be sent if you start interaction with the response, so add the following:
System.err.println(httpCon.getResponseCode());
as per the post, and see if that works?

How to Read/Save Text from a URL in using URLConnection

I am totally new to Android but want to make a simple Android application that displays the state of my LEDs that I have on my breadboard. So far, I've used an ESP8266 to create a server that says "LED ON" (using this guide) and now I want to just display that string on my app in a textview or something.
Every helpful online resource I've seen uses the outdated apache HTTPClient method in Android Studio, but I need to use URLConnect on API 23. Below is what I have so far. When I try stepping through the code, the exception handler gets called when it executes the line starting with "BufferedReader", so I know there's something going on around there.
NOTE: I've added the following to my Android Manifest as well:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Anyone know what's going on, or can fix my code? Thanks for any help! As a beginner to Android programming, I really appreciate it! Below is the code in my .java file.
public void run ()
{
esp_message = (EditText)findViewById(R.id.esp_msg_txb);
btn_connect = (Button)findViewById(R.id.button);
btn_connect.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
try {
URL url = new URL("http://thing.local/led/1");
URLConnection yc = url.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
yc.getInputStream()));
String inputLine;
StringBuilder builder = new StringBuilder();
while ((inputLine = in.readLine()) != null)
builder.append(inputLine.trim());
in.close();
String message = builder.toString();
esp_message.setText(message);
}
catch (Exception ex) {
Log.e("Fail 1", ex.toString());
//Toast.makeText(getApplicationContext(),"Invalid IP Address", Toast.LENGTH_LONG).show();
Log.i("Error on load data:", "" + ex.getMessage());
}
}
}).start();
}
}
);
}

Sending data from Android to a PHP server

I am having an application in android and I want to send the latitude and longitude of the android mobile to the web PHP server through a url (like=..mydata.php?lat=76867&long=87979). I am having the php code that saves the data in database if this url is hit.
All I am not getting is that how to send the latitude and longitude through my android mobile phone to the PHP server.
Building upon #DarkXphenomenon answer, make sure you have the right permissions.
// to retrieve location
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
// to retrieve location
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
// to send data
<uses-permission android:name="android.permission.INTERNET"/>
Then in your java class you can use this code to send the data to the php file. Make sure to catch any exceptions.
String and = "&";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://my site.com/gpsdata.php?imei="+imei+and+"lat="+lat+and+"lng="+lng+and+"alt="+alt+and+"spd="+speed);
try {
httpclient.execute(httppost);
Log.d(TAG, "Data sent!");
} catch (ClientProtocolException e) {
Toast.makeText(this,
"Client protokol exception ", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(this,
"IO exception " + e.getMessage(), Toast.LENGTH_LONG)
.show();
}
You also need to make sure that your location variables such as latitude or longitude are strings otherwise you will get some unexpected errors. Normally the location variables would be a double or a float. To convert a double to a string, excecute
String Longitude = Double.toString(doubleToConvertToString);
And likewise a Float to a String
String Longitude = Float.toString(doubleToConvertToString);
The manifest needs to contain
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET" />`
Update:
Network connections are no longer allowed in the UI thread. You need to then issue an HTTP get wrapped in an AsyncTask<> which will be parsed and interpreted by your PHP backend.
An example is at http://developer.android.com/training/basics/network-ops/connecting.html

Sometimes my app crashes with UnknownHostException

In my app i have access to web server. It works fine in Some phones but while testing in Samsung Galaxy
Model No - GT-S5830i
Android Version - 2.3.6
it keeps on showing Unknown host exception. I have checked the url from browser its working fine.
private void submitUploadData(String url ,Map<String, String> param) throws IOException
{
URL siteUrl;
try {
siteUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) siteUrl.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
Set getkey = param.keySet();
Iterator keyIter = getkey.iterator();
String content = "";
for(int i=0; keyIter.hasNext(); i++) {
Object key = keyIter.next();
if(i!=0) {
content += "&";
}
content += key + "=" + param.get(key);
}
out.writeBytes(content.trim());
out.flush();
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = "";
while((line=in.readLine())!=null) {
System.out.println(line);
}
in.close();
//Intent home = new Intent(SyncHttp.this,TimeAndExpensesSKActivity.class);
//startActivity(home);
db.updateTimeExported(1);
db.updateExpensesExported(1);
db.close();
db.close();
if(db.getLogCount()==0){
db.insertSyncDateDetails(getDateandTime());}
else{
db.updateSyncDateDetails(1, getDateandTime());}
} catch (MalformedURLException e) {
e.printStackTrace();
}
this.setResult(FINISH_RESULT);
db.close();
}
I have already added permissions
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
I am really confused why this exception occurring.
Thanks for your help guys.
My app did this too. This usually caused by unstable network connection. What I did was catching this UnknownHostException and modify the code in a way that if UnknownHostException happened, I try to re-fetch the URL again, after several miliseconds sleep.
The basic algorithm is something like this:
private void submitUploadData(String url ,Map<String, String> param) throws IOException
{
URL siteUrl;
boolean isDataSubmitted = false;
while(!isDataSubmitted){
try {
//do your complicated http process
isDataSubmitted = true;
} catch(UnknownHostException uhe){
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
I have also experienced some issues using URLConnections especially HTTPS on the Samsung Galaxy TAB, but i would imagine it probably occurs on other models as well since there are a ton of devices with the same name but made for different markets and mobile providers.
So far i haven't found a way around sorry, since i tend to avoid the URLConnection class due to a ton of other issues it has.
I suggest using the Apache HTTP Client to communicate with your API's. you can google a ton of examples of using it.
Also when looking at your code i would suggest reading a bit more into the try-catch-finally block statements in java. it is really important to properly close connections at the end or in case of errors.
Other possibilities are:
There is no connection of any sort active (mobile or wifi)
You are missing the "http://www." in your url.
I think calling close() on the DataOutputStream before you recieve your input might close the whole connection - try commenting out that line.
Have you checked the URL from the phone's browser?
Please log the URL you pass to the function and try it in your phone's browser. I would think of missing/incorrect protocol specifier and or URL string formation issues of which this particular phone is unforgiving.

Categories

Resources