Getting text from internet - java

If you go to http://www.elven.ee/ip/ - you can see it gives ip. If you refresh, it gives different port.
How can I get that IP into android? I don't know how to make it also update after like every 5 seconds, but right now I want to know how can i get it into my phone. I want to display it as TextView :).

#mopsled solution did not work for me, so here is mine:
public class TestActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = (TextView) findViewById(R.id.textView1);
String ip = "";
final DefaultHttpClient httpClient = new DefaultHttpClient();
final HttpGet httpGet = new HttpGet("http://www.elven.ee/ip/");
try {
final HttpResponse response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 200) {
ip = getString(response);
}
} catch (final ClientProtocolException e) {
e.printStackTrace();
} catch (final IOException e) {
e.printStackTrace();
}
tv.setText(ip);
}
private static String getString(HttpResponse response) {
final HttpEntity retEntity = response.getEntity();
if (retEntity != null) {
InputStream instream = null;
try {
instream = retEntity.getContent();
} catch (final IllegalStateException ise) {
ise.printStackTrace();
} catch (final IOException ioe) {
ioe.printStackTrace();
}
final String result = convertStreamToString(instream);
return result;
} else {
return "";
}
}
private static String convertStreamToString(final InputStream is) {
final BufferedReader reader = new BufferedReader(new InputStreamReader(is));
final StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (final IOException ioe) {
ioe.printStackTrace();
} finally {
try {
is.close();
} catch (final IOException ioe) {
ioe.printStackTrace();
}
}
return sb.toString().trim();
}
}

EDIT: Fixed code
Try a HTTPURLConnection (a simplified version of an example found here):
StringBuilder content = new StringBuilder();
try {
URL url = new URL("http://www.elven.ee/ip/");
URLConnection urlConnection = url.openConnection();
BufferedReader bufferedReader =
new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
content.append(line + "\n");
}
bufferedReader.close();
} catch(Exception e) {
e.printStackTrace();
}
String myIp = content.toString();

Related

Trouble with "inputstream" when creating mobile app that downloads weather information (with AsyncTask)

I'm trying to make a mobile app that downloads info from the openweathermap.org apis. For example, if you feed that app this link: http://api.openweathermap.org/data/2.5/weather?q=Boston,us&appid=fed33a8f8fd54814d7cbe8515a5c25d7 you will get the information about the weather in Boston, MA. My code seems to work up to the point where I have to convert the input stream to a string variable. When I do that, I get garbage. Is there a particular way to do this seemingly simple task in a proper way? Here is my code so far...
private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return downloadUrl(urls[0]);
} catch (IOException e) {
return null;
}
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
TextView test = (TextView) findViewById(R.id.test);
if(result!=null) test.setText(result);
else{
Log.i(DEBUG_TAG, "returned result is null");}
}
}
private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.i(DEBUG_TAG, "The response is: " + response);
is = conn.getInputStream();
String text = getStringFromInputStream(is);
//JSONObject json = new JSONObject(text);
//try (Scanner scanner = new Scanner(is, StandardCharsets.UTF_8.name())) {
//text = scanner.useDelimiter("\\A").next();
//}
//Bitmap bitmap = BitmapFactory.decodeStream(is);
return text;
}catch(Exception e) {
Log.i(DEBUG_TAG, e.toString());
}finally {
if (is != null) {
is.close();
}
}
return null;
}
private static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
Check this library . Is An asynchronous callback-based Http client for Android built on top of Apache’s HttpClient libraries.

IOException error to connect to wamp server with eclipse?

I have a problem with connecting to WAMP server with my android program that I made with eclipse....
This is my class:
public class Webservice {
public static String readurl(String url)
{
try {
HttpClient client = new DefaultHttpClient();
HttpPost method = new HttpPost(url);
HttpResponse response = client.execute(method);
InputStream inputStream = response.getEntity().getContent();
String resault = ConvertInputStream(inputStream);
return resault;
}
catch (ClientProtocolException e) {
//e.printStackTrace();
Log.i("Log", "Protocol");
}
catch (IOException e) {
//e.printStackTrace();
Log.i("Log", "IOException");
}
return "read";
}
private static String ConvertInputStream(InputStream inputStream)
{
try
{
BufferedReader reader = new BufferedReader(new
InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
builder.append(line);
}
return builder.toString();
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
}
And this is my activity code:
public class NotesActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String resault = Webservice.readurl("http://localhost/note-server");
Log.i("Log", "Resault: " + resault);
When I run, it gives me "IOException" because of the "Log" in my class under the IOException, and at the end give me "Result: read"!!!!!
How can I fix that?
If you are running on an emulator then you should use 10.0.2.2 instead of localhost.
See this post.

android set data in external database

i would like to write data in an external mysql database with my android app.
this class works for that:
public class SendingData extends AppCompatActivity {
Intent intent = null;
private class LoadingDataURL extends AsyncTask<String, String, JSONArray> {
#Override
protected JSONArray doInBackground(String... params) {
URL url;
HttpURLConnection urlConnection = null;
JSONArray response = new JSONArray();
try {
url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
String responseString = readStream(urlConnection.getInputStream());
intent = new Intent(SendingData.this, Overview.class);
startActivity(intent);
response = new JSONArray(responseString);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null)
urlConnection.disconnect();
}
return response;
}
private String readStream(InputStream in) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
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();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loading_data);
String firstname = "Max";
String secondname= "Mustermann";
LoadingDataURL client = new LoadingDataURL();
client.execute("https://domain.com/index.php?"+
"fristname="+fristname+
"&secondname="+secondname);
}
}
My Problem is, that if in my strings (fristname, secondname) is an & or ? or any special characters, the entry will not be save correctly.
any ideas? :)
Use the URLEncoder class.
Try this please
String fn = URLEncoder.encode(fristname, "utf-8");
String sn = URLEncoder.encode(secondname, "utf-8");
LoadingDataURL client = new LoadingDataURL();
client.execute("https://domain.com/index.php?"+
"fristname=" + fn + "&secondname=" + sn);
Note: Don't encode the full url, just the parameter values.

How to get Java script variable from HTML using HttpClient

I need to get the js variable from HTML. I get html from server using HttpCLient, and try to search "src" in stringBuilder.
I want to get image URL shown on page.
Thml sting that i parsed.
How to get this variable?
< img id="h5" src="8.jpg" border="0">
#Override
protected String doInBackground(Void... params) {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 30 * 1000);
HttpConnectionParams.setSoTimeout(httpParameters, 30 * 1000);
httpclient = new DefaultHttpClient(httpParameters);
httpGet = new HttpGet(url);
httpGet.setHeader("Accept-Encoding", "gzip");
//Запрос
HttpResponse response = null;
try {
response = httpclient.execute(httpGet);
} catch (IOException e) {
e.printStackTrace();
}
InputStream instream = null;
try {
instream = response.getEntity().getContent();
} catch (IOException e) {
e.printStackTrace();
}
Header contentEncoding = response.getFirstHeader("Content-Encoding");
if ((contentEncoding != null) && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
try {
instream = new GZIPInputStream(instream);
} catch (IOException e) {
e.printStackTrace();
}
}
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(instream, "utf-8"), 8);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
if (line.contains("\" src"))
{
sb.append(line).append("\n");
}}
} catch (IOException e) {
e.printStackTrace();
}
try {
instream.close();
} catch (IOException e) {
e.printStackTrace();
}
String result = sb.toString();
Log.i("Do id back", " ");
return result;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
txtUrl.setText(result.toString());
Log.i("on Post"," ");
}
}
You can use an HTML parser, e.g. jsoup.

Reading HttpURLConnection

I've been trying to figure out how to read a HttpURLConnection. According to this example: http://www.vogella.com/tutorials/AndroidNetworking/article.html , the following code should work. However, readStream never fires, and I'm not logging any lines.
I do get that the InputStream is passed through the buffer and all, but for me the logic breaks down in the readStream method, and then mostly the empty string 'line' and the while statement. What exactly is happening there / should happen there, and how would I be able to fix it? Also, why do I have to create the url in the Try statement? It gives back a Unhandled Exception; java.net.MalformedURLException.
Thanks in advance!
static String SendURL(){
try {
URL url = new URL("http://www.google.com/");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
readStream (con.getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
return ("Done");
}
static void readStream(InputStream in) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
Log.i("Tag", line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
There are a bunch of things wrong with the code I posted in the question. Here is a working example:
public class GooglePlaces extends AsyncTask {
public InputStream inputStream;
public GooglePlaces(Context context) {
String url = "https://www.google.com";
try {
HttpRequest httpRequest = requestFactory.buildGetRequest(new GenericUrl(url));
HttpResponse httpResponse = httpRequest.execute();
inputStream = httpResponse.getContent();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
try {
for (String line = null; (line = bufferedReader.readLine()) != null;) {
builder.append(line).append("\n");
Log.i("GooglePlacesTag", line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
It appears you are not connecting your HTTPUrlClient try con.connect()

Categories