Reading HTML source from android app - android

I'm trying to get the HTML source in a string from a web site that the user enters, the code I have so far looks like this:
public String getURLContent(String url)
{
try
{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
ResponseHandler<String> resHandler = new BasicResponseHandler();
String page = httpClient.execute(httpGet, resHandler);
return page;
}
catch (ClientProtocolException e)
{
e.printStackTrace();
return "";
}
catch (IOException e)
{
e.printStackTrace();
return "";
}
}
Every time I try to run this I hit the second catch (IOException), which according to the documentation means the server failed to give a valid response... I am testing this with sites like "http:\www.google.com\", so they should definitely be responding

Your code is ok. Make sure you paste full website path : http://www. [page] . [domain] eg.: http://www.google.com
And add this PERMISSION to AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
just before (if it is new project):
<application android:label="#string/app_name">
Full example:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="10"/>
<uses-permission android:name="android.permission.INTERNET" />
<application android:label="#string/app_name">
<activity android:name="MyActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>

Unless you want to do some custom parsing with the whole string, I would advise you to use an HTML parser lib. I use HTML cleaner, showed here.
That makes all the horse work for you.

Related

Not able to send simple GET Http request

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.

REST request on Android

I'm writing my first Android app where the first thing to do is collect a list of maps from a server, but I'm having difficulty getting a simple REST request working. I've been following a number of tutorials and am trying to employ both AsyncTask and HttpURLConnection to do this properly.
For my simple initial test, I just call getMapsJson, with serverUrl set to "http://httpbin.org/ip" (just to make sure it's sending and receiving data correctly).
Code
public String getMapsJson()
{
Log.d(Globals.tag, ">> getting maps json from " + serverUrl.toString());
String output = "";
new GetMapsJsonTask().execute(serverUrl);
return output;
}
private class GetMapsJsonTask extends AsyncTask<URL, Void, String>
{
private HttpURLConnection connection = null;
protected String doInBackground(URL... url)
{
String output = "";
try
{
connection = (HttpURLConnection) url[0].openConnection();
connection.setRequestMethod("GET");
Log.d(Globals.tag, "connection opened!");
InputStream in = new BufferedInputStream(connection.getInputStream());
Log.d(Globals.tag, "input stream captured");
output = readStream(in);
Log.d(Globals.tag, "stream read");
}
catch (IOException e)
{
Log.d(Globals.tag, (e.getMessage() == null ? "IO Exception" : "IO : " + e.getMessage()));
}
finally
{
return output;
}
}
protected void onPostExecute(String json)
{
Log.d(Globals.tag, "Json response: " + json);
}
}
private String readStream(InputStream in) throws IOException
{
Log.d(Globals.tag, "entering readStream");
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = reader.readLine();
String output = line;
while((line = reader.readLine()) != null)
output += line;
return output;
}
AndroidManifest.xml
I have the android.permission.INTERNET line in there, but I'm not positive it's in the correct location. May cause issues?
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.northstar.minimap"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="17"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name="com.northstar.minimap.Globals"
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.northstar.minimap.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.northstar.minimap.MapActivity"
android:label="#string/title_activity_map"
android:parentActivityName="com.northstar.minimap.MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.northstar.minimap.MainActivity" />
</activity>
</application>
</manifest>
Output
Logcat yields the following lines:
12-01 21:31:44.727 2188-2188/com.northstar.minimap D/Minimap﹕ >> getting maps json from http://httpbin.org/ip/
12-01 21:31:44.727 2188-2232/com.northstar.minimap D/Minimap﹕ connection opened!
12-01 21:31:45.106 2188-2232/com.northstar.minimap D/Minimap﹕ IO: http://httpbin.org/ip/
12-01 21:31:45.106 2188-2188/com.northstar.minimap D/Minimap﹕ Json response:
Basically, something's causing an IOException, and I'm not sure what - the exception's getMessage isn't exactly verbose. Do I have to do any configuration for the emulator (JellyBean, API level 17)?
Thanks!

Connecting to WCF webservices using JSON on Android

Recently i am developing Android applications
what i wanted to do is consume a web services
from .net WCF into my application
Here is my Client Code
import java.io.InputStream;<br>
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;<br>
import org.apache.http.HttpResponse;<br>
import org.apache.http.client.methods.HttpGet;<br>
import org.apache.http.impl.client.DefaultHttpClient;<br>
import org.json.JSONObject;<br>
import android.R.string;<br>
import android.os.Bundle;<br>
import android.app.Activity;<br>
import android.view.Menu;<br>
import android.view.View;<br>
import android.widget.TextView;<br>
public class MyPamIndex extends Activity {
private final static String SERVICE_URI = "http://172.30.2.95:9000/JSON/MyPam.svc";
private TextView NabVals;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_pam_index);
NabVals = (TextView)findViewById(R.id.textView2);
}
public void OnRefreshClick(View button)
{
try {
// Send GET request to <service>/GetVehicle/<plate>
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(SERVICE_URI + "/ProductID/" + "1");
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(request);
HttpEntity responseEntity = response.getEntity();
// Read response data into buffer
char[] buffer = new char[(int)responseEntity.getContentLength()];
InputStream stream = responseEntity.getContent();
InputStreamReader reader = new InputStreamReader(stream);
reader.read(buffer);
stream.close();
JSONObject vehicle = new JSONObject(new String(buffer));
NabVals.setText(vehicle.getString("NabValue"));
// Populate text fields
} catch (Exception e) {
e.printStackTrace();
}
}
when i run the apps it have an error
in
HttpResponse response = httpClient.execute(request);
i have search the entire forum but found nothing
i already add my android manifest file but still does not working
please help me
this is my Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.core.mypam"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="anroid.permission.INTERNET"></uses-permission>
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="16" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.core.mypam.MyPamIndex"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
"http://172.30.2.95:9000" is not my machine IP but its located on other PC within same LAN
Please help me
You're making a network request on the UI thread. That is no longer allowed and, and will raise an exception. You need to move your code into an AsyncTask. Google NetworkOnMain for a plethora of examples.

An established connection was aborted by the software in your host machine (VS dev server)

I've seen similar posts about this problem, but none of them relate to the use of the Visual Studio development server for ASP .NET.
I'm receiving the following error.
An established connection was aborted by the software in your host machine.
And I'm executing the following code:
String employeesJson = client.downloadString("http://localhost:60000/Api/Employee/GetEmployees.aspx");
When I run this in a regular webbrowser (Chrome 21 or Internet Explorer 10) it runs just fine. I get the JSON result that I want.
And my WebClient class being used (under the variable "client") is defined as follows.
public class WebClient {
private HttpClient httpClient;
public WebClient() {
httpClient = new DefaultHttpClient();
}
public String downloadString(String url) throws IOException {
HttpGet get = new HttpGet(url);
try {
HttpResponse response = httpClient.execute(get); //this is where the error occurs.
HttpEntity entity = response.getEntity();
if(entity != null) {
InputStream stream = entity.getContent();
InputStreamReader streamReader = new InputStreamReader(stream);
BufferedReader bufferedReader = new BufferedReader(streamReader);
StringBuilder builder = new StringBuilder();
String line = null;
try {
while ((line = bufferedReader.readLine()) != null) {
builder.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return builder.toString();
}
//catch all the types of exceptions this method can throw. catching "Exception" is considered bad.
} catch (ClientProtocolException e) {
e.printStackTrace();
}
return null;
}
}
My AndroidManifest.xml file looks like this:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="specialisering.android"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="15" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
face same problem, it was firewall stoping it .... so turned off the firewall and it working now... :)
I can't believe I didn't seek an answer from the documentation. It clearly states that 127.0.0.1 is the IP of the emulator itself, while 10.0.2.2 is the IP of the developer machine.
Changing from localhost to 10.0.2.2 solved my issue.

httpPost takes to long and get this exception : java.net.SocketException: The operation timed out

i connect to restful web service from android . I need to use httpPost to
add information. But it takes to long and i get exception.
java.net.SocketException: The operation timed out
on the other hand i can make httpGet , i don't take any exception
the code is here.
ip equals to my computer's ip at local are network. ip=10.80.20.20
HttpClient httpclient = new DefaultHttpClient();
String url="http://"+ip+"/projectt/source/applySurvey";
HttpPost httppost = new HttpPost(url);
String strSurveyId=new Long(surveyId).toString();
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("surveyId",strSurveyId));
nameValuePairs.add(new BasicNameValuePair("questionId", "4"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
} catch (ClientProtocolException e) {
e.printStackTrace();
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
e.getCause();
My manifest file is here
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mobil.survey.project"
android:versionCode="1"
android:versionName="1.0">
<uses-permission android:name="android.permission.INTERNET"/>
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".categoryList"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".firmsList" android:label="#string/app_name"></activity>
<activity android:name=".surveiesList" android:label="#string/app_name"></activity>
<activity android:name=".survey" android:label="#string/app_name"></activity>
</application>
</manifest>
Which restful web service is defined web.xml is here
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>projectt</display-name>
<servlet>
<servlet-name>FormValidator</servlet-name>
<servlet-class>com.project.servlets.FormValidator</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FormValidator</servlet-name>
<url-pattern>/FormValidator</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.project.resources</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/source/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
and the uri resource I connected is here
#Path("/applySurvey")
public class AppliedSurveyResource {
#GET
#Produces( MediaType.APPLICATION_JSON)
public List<WSCategory> getCategories() {
List<WSCategory> categories = new ArrayList<WSCategory>();
categories.addAll( CategoryProvider.instance.getModel() );
return categories;
}
#POST
#Produces(MediaType.TEXT_HTML)
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public void newTodo(
#FormParam("surveyId") Long surveyId,
#FormParam("questionId") Long questionId,
#FormParam("cellId") String cellId,
#Context HttpServletResponse servletResponse
) throws IOException {
PRAppliedSurvey appliedSurvey=new PRAppliedSurvey();
appliedSurvey.setSurveyId(surveyId);
appliedSurvey.setQuestionId(questionId);
appliedSurvey.setCellId(cellId);
java.util.Date today = new java.util.Date();
System.out.println(new java.sql.Timestamp(today.getTime()));
appliedSurvey.setApplyDt(new java.sql.Timestamp(today.getTime()));
try {
appliedSurvey.store();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*Todo todo = new Todo(id,summary);
if (description!=null){
todo.setDescription(description);
}
TodoDao.instance.getModel().put(id, todo);
URI uri = uriInfo.getAbsolutePathBuilder().path(id).build();
Response.created(uri).build();
servletResponse.sendRedirect("../create_todo.html");
*/
}
}
}
Try running it in a different thread using AsyncTask. The UI thread has a pretty low threshold before it throws a timeout. This is to keep the UI from freezing for the user.
http://developer.android.com/reference/android/os/AsyncTask.html

Categories

Resources