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

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();
}
}
);
}

Related

Issues with http request in Android

I am new to this website, so if i do something wrong please tell me.
I am trying to establish a connection between my node.js server and my android app. For example, I'm trying to connect a page called showWithAuth, where i need to authenticate with digest stategy.
For this purpose i use Authenticator :
Authenticator.setDefault(new Authenticator()
{
#Override
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication (username, password.toCharArray());
// System.out.println(pa.getUserName() + ":" + new String(pa.getPassword()));
}
});
My real issue is when i try to establish the connection :
try {
URL url = new URL(strURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
in = new BufferedReader(new InputStreamReader(connection
.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
sb.append(line);
}
System.out.println(sb);
/*connection.setInstanceFollowRedirects(false);
int status = connection.getResponseCode();
InputStream is;
if (status >= 400 && status <= 499) {
throw new Exception("Bad authentication status: " + status); //provide a more meaningful exception message
}
else
{*/
//connection.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) ");
//connection.setRequestProperty("Accept", "*/*");
/*is = connection.getInputStream();
}
byte[] buffer = new byte[8196];
int readCount;
final StringBuilder builder = new StringBuilder();
while ((readCount = is.read(buffer)) > -1) {
builder.append(new String(buffer, 0, readCount));
}
String response = builder.toString();
System.out.println(response);*/
} catch (java.net.ProtocolException e) {
sb.append("User Or Password is wrong!");
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
The issue i have is a filenotfoundexception, at this line :.getInputStream()));
The response of the server is a 401 : bad authentication status
I saw some people having the same issue i deal with, but i tried every single solution without getting anything better.
If you could help me to get what i do wrong ! Thank you !
PS: the commented code was also tried.
PS2: sorry for being so long.
Edit: Just to say also that this code is working on Netbeans with Java only, but not in Android Studio
Please try by adding the
<uses-permission android:name="android.permission.INTERNET" />
To your AndroidManifest.xml file, this may solve your problem.

Loopj (AsyncHttpClient get method) doesnt return response in Android Unit Test

I am trying to create Unit test on Android project which is working with URL requests. I use loopj library but something doesn't work. Internet is enabled in my manifest:
<uses-permission android:name="android.permission.INTERNET" />
Java code in a test method:
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.yahoo.com", new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
System.out.println(response); // <------ I never get here!?!?!
}
});
Folowing procedure (without loopj) works in same unit test method:
URL yahoo;
yahoo = new URL("http://www.yahoo.com/");
BufferedReader in;
in = new BufferedReader(new InputStreamReader(yahoo.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
in.close();
It seems like loopj requests dont work in unit test class but it works normal in basic Activity class. Any suggestion?
The problem is since loopj uses android.os.AsyncTask which doesnt work in unit test environment.
Key to success is "runTestOnUiThread" method.
public void testAsyncHttpClient() throws Throwable {
final CountDownLatch signal = new CountDownLatch(1);
final AsyncHttpClient httpClient = new AsyncHttpClient();
final StringBuilder strBuilder = new StringBuilder();
runTestOnUiThread(new Runnable() { // THIS IS THE KEY TO SUCCESS
#Override
public void run() {
httpClient
.get(
"https://api.twitter.com/1/users/show.json?screen_name=TwitterAPI&include_entities=true",
new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
// Do not do assertions here or it will stop the whole testing upon failure
strBuilder.append(response);
}
public void onFinish() {
signal.countDown();
}
});
}
});
try {
signal.await(30, TimeUnit.SECONDS); // wait for callback
} catch (InterruptedException e) {
e.printStackTrace();
}
JSONObject jsonRes = new JSONObject(strBuilder.toString());
try {
// Test your jsonResult here
assertEquals(6253282, jsonRes.getInt("id"));
} catch (Exception e) {
}
assertEquals(0, signal.getCount());
}
Ful thread:
https://github.com/loopj/android-async-http/issues/173
Careful that you haven't forgotten to declare network access in the manifest i.e.
<manifest ....>
...
<uses-permission android:name="android.permission.INTERNET" />
...
</manifest>
An asynchronous callback-based Http client for Android built on top of Apache’s HttpClient libraries. All requests are made outside of your app’s main UI thread, but any callback logic will be executed on the same thread as the callback was created using Android’s Handler message passing.
Check http://loopj.com/android-async-http/ this may help you !

Android get web page source

I want to get the source code of a web page that the users enters. When he presses the button, he should see the source in a TextView. This is my code:
final Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
try {
URL url = null;
url = new URL(myEditText.getText().toString());
URLConnection conn = url.openConnection();
BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
myTextView.append(line);
}
} catch (Exception e) {
Log.e("ERR",e.getMessage());
}
}
});
When I run it I get a NullPointerException at
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
.-->Println needs a message.
I don't know what is wrong, since this is from a video tutorial. I have written <uses-permission android:name="android.permission.INTERNET"/> in Manifest so, everything should be allright.
try this.
url = new URL("http://www.stackoverflow.com");
if it works then you need to set validation for like isValidUrl() ?
Because user may have entered wrong URL.
if(!TextUtils.isEmpty(myEditText.getText()))
url = new URL(myEditText.getText().toString());
else
url="";
or if you are using latest version check StrictMode and remove it
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
also check the android is network available or not

Can't connect to local area server with asp.net page on Android

I'm new here and I wish I won't make any bloomer :)
I'm developing some android app and have stucked in connecting to other computer, where I've installed ASP.net page. I can't emulate it due to problems with connecting to host.
The code that I'm using:
public class SPCChartViewerActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String strData = urlData("http://[server]/SPCOnline/SQLQuery.aspx?query=SELECT%20NAME%20FROM%20SPC_CHARTS");
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText(strData);
}
private String urlData(String urlString){
URLConnection urlConnection = null;
URL url = null;
String string = null;
try {
url = new URL(urlString);
urlConnection = url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(inputStreamReader);
StringBuffer stringBuffer = new StringBuffer();
while((string = reader.readLine()) != null){
stringBuffer.append(string + "\n");
}
inputStream.close();
string = stringBuffer.toString();
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return string;
}
}
In tag [server] I've put:
that computer's name: http://miltstx155srv01/SPCOnline/SQLQuery.aspx?query=SELECT%20NAME%20FROM%20SPC_CHARTS
In this case I receive java.net:UnknownHostException
that computer's IP: http://10.72.152.163/SPCOnline/SQLQuery.aspx?query=SELECT%20NAME%20FROM%20SPC_CHARTS
In this case I receive java.net:FileNotFoundException
If I ommit the "http://" I receive java.net:Protocol Not Found
Ok, maybe something with my company's DNS. So I've put this page on my computer, which is also running AVD emulator. So the url is now: http://10.0.2.2/SPCOnline/SQLQuery.aspx?query=SELECT%20NAME%20FROM%20SPC_CHARTS - but still java.net:UnknownHostException.
Of course clause uses-permission android:name="android.permission.INTERNET" is added to manifest.
Still, every example written upper works fine with webbrowser (of course except 10.0.2.2 - but changing it to localhost makes it work).
No idea, I've spent whole day testing it. Can anyone help?

How to use webview or open URL in AndEngine - Android

I'm utilizing a game engine called AndEngine (which I'm completely new to) in my Android app. I need to load a different URL from the application based on what position an onscreen joystick is in (uploading to a .cgi server). The dilemma is that I cannot open a URL connection! This may seem simple, but I've looked everywhere, tried multiple solutions and nothing's worked. In basic Android, I've always used a WebView (loadUrl() method), and it worked well. However, I have no idea to how to create a webview while also using AndEngine. My preference is that the connection did not show (loaded underneath the AndEngine scene?) because I will need the screen for other things. I've also tried other solutions. I just tried this code, but when I checked the server, nothing was opened:
#Override
public void onLoadResources() {
//methods n/a to this question
try {
URL url = new URL(setUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
readStream(con.getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
return scene; // AndEngine return statement
}
private void readStream(InputStream in) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
**I've tried using the HTTPConnection class before (without AndEngine) to open up a URL, but to no avail. So it may be that I was just doing something wrong here. Using AndEngine GLES2. If more info is needed, let me know (this is my first question on SO).
Also tried setting up my .xml layout on AndEngine using
#Override
protected int getLayoutID() {
return R.layout.main;
}
but it says: "The method getLayoutID() of type Control must override or implement a supertype method"
Edit in response to Nicolas Gramlich: Internet permissions were set and compiler was originally at 1.6. Still don't know what the issue is.
xml
<manifest xlmns:android...>
...
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
Set java compiler compliance to 1.6
I solved my issue. I had to run all network operations on a thread separate from the main one (else it will throw a NetworkOnMainThread exception). I don't know why nothing else worked, but this did the trick! Here I'm creating a new thread with the action I want to perform, and then starting it after exceptions are taken care of. I found my answer here
new Thread(new Runnable() {
public void run() {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("your_url");
try {
HttpResponse response = httpClient.execute(httpGet, localContext);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();

Categories

Resources