Downloading html source code and loading it - java

I found this code from here download html source android? . But when I try running it, my program keeps crashing. I have already added the internet permission in. Any ideas?
Edit: Here is the full error message. 08-02 00:16:47.364: E/EmbeddedLogger(1577): Error getting package label: com.jimmyc.lawrenceh.schedulinglookup
Edit2: It works on Android 2.2 but it doesn't work on Android 4.0/3.0.
private void initialize() {
//initialize variables here
try {
getHtml();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void getHtml() throws ClientProtocolException, IOException {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("http://www.yahoo.com");
HttpResponse response = httpClient.execute(httpGet, localContext);
String result = "";
BufferedReader reader =
new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = null;
while ((line = reader.readLine()) != null){
result += line + "\n";
// Toast.makeText(Connect.this, line.toString(), Toast.LENGTH_LONG).show();
}
}

I think you are trying to download the HTML code in the UI Thread. Try to download it in the background, using AsynkTask
Edit. If you say that it works on Android 2.2 but it doesn't work on Android 4.0/3.0 I'm completely sure you are trying to download it in the UI thread. From Android 3.0, you can't do long process in the UI thread because you can block it. You must do the download in a different thread
PS. Sorry for my english.

Related

Get result from php in android studio using simple runnable threads without any external libraries

So, I know this might seems like a repeated question, but bear with me for a moment. In Android Studio, instead of using any external libraries (i.e., no JSON, no Volley, no Retrofit, nothing external), I plan to use simple runnable threads. These will fetch data using PHP stored on the localhost through the IP address of the WiFi which my system is using.
I know how to send a PHP update (the actual update codes are in PHP script), it's done like this:
Runnable runnableToUpdateDb = new Runnable() {
#Override
public void run() {
Log.d("DEBUG","RUNNING RUNNABLE");
try {
URL url = new URL("http://192.168.43.242/myapi/php_name.php");
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.connect();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String response = bufferedReader.readLine();
Log.d("DEBUG", response);
httpURLConnection.disconnect();
}catch (Exception e){
Log.d("DEBUG",e.toString());
}
}
};
And then simply running the PHP using thread upon the press of the button by:
Thread threadToUpdateDb = new Thread(runnableToUpdateDb);
threadToUpdateDb.start();
Now, the problem is in setting up a TextView that shows the updated/new data from the database though a different PHP.
The id I've described for this TextView in the layout is:
android:id="#+id/getdata"
I need help for implementing it in MainActivity.
The output for PHP is in the form of:
<br>8<br>
Here's how you perform a HTTP GET to an URL using plain Android. In this case I choose an AsyncTask so it would run the request aside from the Main Thread:
private class TareaGetFromDB extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String URL = params[0];
String response = null;
try {
// Create an HTTP client
HttpClient client = new DefaultHttpClient();
HttpGet post = new HttpGet(URL);
// Perform the request and check the status code
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == 200) {
// code 200 equals HTTP OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
try {
response = IOUtils.toString(content, "utf-8");
} catch (Exception ex) {
// TODO handle exception
}
}
} catch(Exception ex) {
// TODO handle exception
}
return response;
}
#Override
protected void onPostExecute(String response) {
TextView myTextView = findViewById(R.id.getdata);
myTextView.setText(response);
}
}
This AsyncTask takes a String (the URL) as argument and returns a String (the response).
So you'll need to call it like this:
new TareaGetFromDB().execute("http://url.to/get/data");
You may need additional work before setting the text to the TextView to remove the surronding <br>, or you can remove them from the server response

Issue in making rest call which actually works fine locally but not in production server

In my java code I'm calling third pary apis. In my local workspace it works pretty well and I'm getting proper response. But When I deploy the war in production, I see in logs, I'm calling the apis and didn't get any response. It sound wierd to me and got stuck with it. Please find the snippet and I'm completely calling api in plain old Java.
private void updateRetailerOrderStatus(String trackingId) {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
System.out.println("Inside updateRetailerOrderStatus By Android");
Order order = orderDao.getOrdersByTrackingId(trackingId);
HttpPost httpPost = new HttpPost("http://SomeDomine/v1/order/delivered");
httpPost.addHeader("Some Key", "Some Value");
httpPost.addHeader("Content-Type", "application/json");
JSONObject json = new JSONObject();
json.put("awb_no", order.getTrackingId());
json.put("order_no", order.getOrderId());
json.put("delivered_date", order.getDeliveredDate().toString());
json.put("status", "delivered");
json.put("carrier", "Delivery");
StringEntity entity = new StringEntity(json.toString());
httpPost.setEntity(entity);
System.out.println(json.toString());
HttpResponse response = httpclient.execute(httpPost);
BufferedReader buffReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer respBuffer = new StringBuffer();
String line = "";
while ((line = buffReader.readLine()) != null) {
System.out.println(line);
respBuffer.append(line);
}
System.out.println("API Response: "+ respBuffer.toString());
} catch(Exception ex) {
System.out.println("Error in fetchToken :"+ ex.getMessage());
System.out.println(ex.getStackTrace());
} finally {
try {
httpclient.close();
} catch(Exception ex) {
System.out.println(ex.getMessage());
}
}
}
My Questions are:
1) Is there a possibility of happening this? If So, Why?
2) Should I call this in saparate thread? But, I didn't see any suggestions of doing it in most of the examples.

Connecting to PHP script through android app [duplicate]

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 9 years ago.
This is the code I have so far.
public void postData(String toPost) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.mywebsite.com/dev/reverser.php");
//This is the data to send
String MyName = toPost; //any data to send
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("action", MyName));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpclient.execute(httppost, responseHandler);
//This is the response from a php application
String reverseString = response;
Toast.makeText(this, "response" + reverseString, Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
Toast.makeText(this, "CPE response " + e.toString(), Toast.LENGTH_LONG).show();
// TODO Auto-generated catch block
} catch (IOException e) {
Toast.makeText(this, "IOE response " + e.toString(), Toast.LENGTH_LONG).show();
// TODO Auto-generated catch block
}
}//end postData()
Can somebody please tell me what is wrong in the following code! I have established that there is a problem in the try catch block only and not anywhere else in the activity. I just do not know what it is or how to correct it.
My PHP code is quite simple. It is something like this -
//code to reverse the string
$reversed = strrev($_POST["action"]);
echo $reversed;
In a comment above you indicated that you are getting a android.os.NetworkOnMainThreadException.
In the most recent versions of Android you are not allowed to do networking on the main thread as it makes the UI unresponsive. Move your code to a different thread using AsyncTask (see the Android developer guide for details) or some other mechanism.
Adding as a seperate answer as the poster requests to do so .
Assumption :
a ) There is a text box that accepts the URL to load
b ) A button which when clicked performs the networking operation on the URL fetched f
Implement a button click listener that calls the following function :
private void URL()
{
String url = txtURL.getText().toString();
new URLTask().execute(new String[] { url });
}
private class URLTask extends AsyncTask<String, Void, String>
{
protected String doInBackground(String... urls)
{
BufferedReader br = null;
String url = urls[0];
StringBuffer sb = new StringBuffer("");
try
{
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost();
request.setURI(new URI(url));
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("param1", "value of param1"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
String line;
br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
while ((line = br.readLine()) != null)
{
sb.append(line + "\n");
}
br.close();
}
catch(Exception e)
{
Toast.makeText(HttpPostActivity.this, "Exception: " + e.toString(), Toast.LENGTH_LONG).show();
}
finally
{
if (br != null)
{
try
{
br.close();
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}
return(sb.toString());
}
protected void onPostExecute(String result)
{
txtContent.setText(result);
}
You need to implement onPostExecute as well . There are other APIS .
Android Async Task Documentation
Try printing out the exception .
Use this code to print out your response . Check the status of the response
HttpResponse response = client.execute(request);
String line;
br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
while ((line = br.readLine()) != null)
{
sb.append(line + "\n");
}
br.close();
}
catch(Exception e)
{
Toast.makeText(HttpPostActivity.this, "Exception: " + e.toString(), Toast.LENGTH_LONG).show();
}
Tell us the exception . It would be easy to pinpoint your problems then .
EDIT : ANSWER :
You are trying to perform a networking operation on the MAIN thread . This is an illegal thing to do . Create a AsyncTask i.e create a seperate thread to do your networking operations .
Android Details of the exception
Stackoverflow question

Response code 500 when accesing rest based web services though eclipse

I am trying to invoke a web service from an Eclipse program. But I am getting response code 500 as response. When I access the URL from IE or Mozilla it works fine for me. My sample Eclipse program:
public static void main(String[] args) {
// Use apache commons-httpclient to create the request/response
HttpClient client = new HttpClient();
Credentials defaultcreds = new UsernamePasswordCredentials("aaa", "aaaa");
client.getState().setCredentials(AuthScope.ANY, defaultcreds);
GetMethod method = new GetMethod("http://localhost:8080/usersByID/2039");
try {
client.executeMethod(method);
InputStream in = method.getResponseBodyAsStream();
// Use dom4j to parse the response and print nicely to the output stream
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder out = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
}
System.out.println(out.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
When I opened the link in IE or Mozilla I am getting exact output. The credentials are correct.
Can any one help to overcome this.
Thanks.

Android 2.2 (level 8) httpclient.execute consistent timeout

I'm attempting to receive a response from a restful service, but receive a timeout. I am able to connect with the browser on my emulator, as I have configured an access point on the emulated device to pass through proxy (at work). Network seems to be fine. I've added:
<uses-permission android:name="android.permission.INTERNET" />
to the AndroidManifest.xml file.
The code is as follows:
public String getInputStreamFromUrl(String url) {
String content = null;
InputStream stream = null;
try {
HttpGet httpGet = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
// Execute HTTP Get Request
HttpResponse response = httpclient.execute(httpGet);
stream = response.getEntity().getContent();
BufferedReader rd = new BufferedReader(new InputStreamReader(stream), 4096);
String line;
StringBuilder sb = new StringBuilder();
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
content = sb.toString();
} catch (Exception e) {
content = e.getMessage();
}
return content;
I know I should return a stream, but for the sake of just displaying some string values in a TextView widget, will suffice, so I'm just using the string to experiment. It consistently hangs on .execute, no matter what URL is passed. I've passed valid IP's as well, with nothin' doin'.
I appreciate your help in advance.
Try this. Put it at the top of the class.
System.setProperty("http.proxyHost", <your proxy host name>);
System.setProperty("http.proxyPort", <your proxy port>);

Categories

Resources