How to get content via url-request? - java

I write application which must show page content(text and images) via url-request. My task requires to do it manually, for example variant such as WebView webView.loadUrl(url.toString()); is not suitable. How to solve this task in another way?

Try using HTTPClient. something like this.
public static InputStream getInputStreamFromUrl(String url) {
InputStream content = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(url));
content = response.getEntity().getContent();
} catch (Exception e) {
Log.("[GET REQUEST]", "Network exception", e);
}
return content; //url content is here.
}

Related

POST an XML file as DOM Document to a php page using Java

I want to POST an XML file as DOM Document to a php page (received using Java).
When the Object is received in the php side. I read/traverse the file as a DOM Documents and send another XML DOcument file as response to the post.
Any directions would be very much appreciated.
Here's my sample Java code..
private Document sendToServerAndFetchResponse(Document xmlDocument) {
Document responseXML = null;
// Create the httpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
// Url to which the post has to be performed.
HttpPost httppost = new HttpPost(
"http://192.168.0.19:3334/cogglrestservice.svc/InsertTrack");
// Make sure the server knows what kind of a response we will accept
httppost.addHeader("Accept", "text/xml");
// Also be sure to tell the server what kind of content we are sending
httppost.addHeader("Content-Type", "application/xml");
try {
StringEntity entity = new StringEntity(xmlDocument.toString(),
"UTF-8");
entity.setContentType("application/xml");
httppost.setEntity(entity);
// execute is a blocking call, it's best to call this code in a
// thread separate from the ui's
HttpResponse response = httpClient.execute(httppost);
BasicResponseHandler responseHandler = new BasicResponseHandler();
String strResponse = null;
if (response != null) {
try {
// Returns the response body as a String if the response was
// successful (a 2xx status code).
// If no response body exists, this returns null. If the
// response was unsuccessful (>= 300 status code), throws an
// HttpResponseException.
strResponse = responseHandler.handleResponse(response);
} catch (HttpResponseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
}
return responseXML;
}
}
DOM is available in PHP, too. Your data (the request body) should be available as stdin. Here is a simple demo:
// create a dom and load the request body
$dom = new DOMDocument();
$dom->loadXml(file_get_contents('php://stdin'));
// create an xpath instance for the document
$xpath = new DOMXpath($dom);
// look for nodes and set the attribute
foreach ($xpath->evaluate('/foo/bar') as $node) {
$node->setAttribute('attr', 'success');
}
// send the header and output the document as string
header('Content-Type: application/xml');
echo $dom->saveXml();
Demo: https://eval.in/161089
You should recognize the methods of DOMDocument from Javas xmlDocument.

HttpClient Intermittent Page Not Found

I use the following code and run the method multiple times, a few times I get a response in GZIP which is what I expect and a few other times I get a response that is completely different(non GZIP page not found). However if I download the same URL multiple times using Mozilla or IE I consistently get the same GZIP response.
Is this an error with the server I am trying to reach to, or do I need to set any parameters to get a consistent response ?
The URL I am trying to download is the following, can you please let me know ?
public static byte[] dowloadURL(URL urlToDownload) {
InputStream iStream = null;
byte[] urlBytes = null;
try {
//HttpClient httpClient = new HttpClient();
org.apache.http.client.
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(urlToDownload.toString());
HttpResponse response = httpClient.execute(httpget);
iStream = response.getEntity().getContent();
urlBytes = IOUtils.toByteArray(iStream);
String responseString = new String(urlBytes);
System.out.println(" >>> The response string for " +urlToDownload.toString()+ " is " +responseString);
} catch (IOException e) {
System.err.printf("Failed while reading bytes from %s: %s",
urlToDownload.toExternalForm(), e.getMessage());
e.printStackTrace();
// Perform any other exception handling that's appropriate.
} finally {
if (iStream != null) {
try {
iStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return urlBytes;
}

Android - How to Download XML Files with Android 4.0?

I will Download XML File with Android 4.0 my old Code works at Android 2.3.3 here:
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
I must have an Example without DefaultHttpClient .
From Gingerbread (2.3) and up, the preferred method for retrieving HTTP data is HttpUrlConnection. You might wanna check this blog post for details. You may also want to check the Javadoc for HttpUrlConnection
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();
}
your problem may be the "strict mode" here.
you have to do http requests with a thread or an AsyncTask.
class RequestTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... params) {
//http request here
//return the response as string
}
#Override
protected void onPostExecute(String result) {
//set the the data you get
}
then:
new RequestTask().execute(yourHttpRequestString)

XML Parsing using Java not getting any Response

am trying to get the XML file from a URL but am getting no Response and the code stops later because the String xml is null, can you tell me whats the problem ?
public String getXmlFromUrl(String url) {
String xml = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
// I printed the response here but I got nothing !
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
return xml;
} catch (Exception e) {
e.printStackTrace();
}
Please be specific in you answers I appreciate your help
Why you are using HTTPPost?? You are not sending any data Even. Try with HttpGet.
Try This :
public String getXmlFromUrl(String url) throws Exception {
return new AsyncTask<String, Void, String>() {
#Override
protected String doInBackground(String... params) {
String xml = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet(params[0]);
HttpResponse httpResponse = httpClient.execute(httpPost);
// I printed the response here but I got nothing !
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
Log.i("DEMO", xml);
} catch (Exception e) {
e.printStackTrace();
}
return xml;
}
}.execute(url).get();
}
Try to start your code from separate thread e.g.
new Thread(new Runnable()
{
#Override
public void run()
{
// TODO your code here
}
}).start();
try this:
try {
items = new ArrayList<String>();
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(new InputStreamReader(
getUrlData(" url")));
while (xpp.getEventType() != XmlPullParser.END_DOCUMENT) {
Log.i(TAG, "doc started");
if (xpp.getEventType() == XmlPullParser.START_TAG) {
if (xpp.getName().equals("entry")) {
items.add(xpp.getAttributeValue(0));
}
}
xpp.next();
}
} catch (Throwable t) {
Toast.makeText(this, "Request failed: " + t.toString(),
Toast.LENGTH_LONG).show();
}
for geturldata()
public InputStream getUrlData(String url) throws URISyntaxException,
ClientProtocolException, IOException {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet method = new HttpGet(new URI(url));
HttpResponse res = client.execute(method);
return res.getEntity().getContent();
}
You should understand Exceptions. The reason xml is null is because 'something' went wrong. This threw an Exception, probably with a good description of what went wrong. When this happens, the Exception is thrown 'up' until someone handles it.
Every subclass of Exception has a different 'flavor' and is thrown in specific cases. This enables you to 'react' on errors. For instance, you could tell the user what went wrong, or log something for debugging sake.
In your case, you 'catch' all exceptions in a single place, when an exception occurs, the code after catch (Exception e) is executed. You do nothing here but printing out some stuff (this will appear orange in your LogCat). Then you continue as if nothing happened. But xml will be null, which is bad for your program, and you apparently didn't notice the LogCat entry because your program crashes at a later point.
This time, Eldhose M Babu solved your problem. Next time, when something else goes wrong (and a lot can go wrong in htttp requests), your program will show the same behavior. Try and read up on exceptions and be careful when you handle them too silently.

How to send simple http post request with post parameters in java

I need a simple code example of sending http post request with post parameters that I get from form inputs.
I have found Apache HTTPClient, it has very reach API and lots of sophisticated examples, but I couldn't find a simple example of sending http post request with input parameters and getting text response.
Update: I'm interested in Apache HTTPClient v.4.x, as 3.x is deprecated.
Here's the sample code for Http POST, using Apache HTTPClient API.
import java.io.InputStream;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
public class PostExample {
public static void main(String[] args){
String url = "http://www.google.com";
InputStream in = null;
try {
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(url);
//Add any parameter if u want to send it with Post req.
method.addParameter("p", "apple");
int statusCode = client.executeMethod(method);
if (statusCode != -1) {
in = method.getResponseBodyAsStream();
}
System.out.println(in);
} catch (Exception e) {
e.printStackTrace();
}
}
}
I pulled this code from an Android project by Andrew Gertig that I have used in my application. It allows you to do an HTTPost. If I had time, I would create an POJO example, but hopefully, you can dissect the code and find what you need.
Arshak
https://github.com/AndrewGertig/RubyDroid/blob/master/src/com/gertig/rubydroid/AddEventView.java
private void postEvents()
{
DefaultHttpClient client = new DefaultHttpClient();
/** FOR LOCAL DEV HttpPost post = new HttpPost("http://192.168.0.186:3000/events"); //works with and without "/create" on the end */
HttpPost post = new HttpPost("http://cold-leaf-59.heroku.com/myevents");
JSONObject holder = new JSONObject();
JSONObject eventObj = new JSONObject();
Double budgetVal = 99.9;
budgetVal = Double.parseDouble(eventBudgetView.getText().toString());
try {
eventObj.put("budget", budgetVal);
eventObj.put("name", eventNameView.getText().toString());
holder.put("myevent", eventObj);
Log.e("Event JSON", "Event JSON = "+ holder.toString());
StringEntity se = new StringEntity(holder.toString());
post.setEntity(se);
post.setHeader("Content-Type","application/json");
} catch (UnsupportedEncodingException e) {
Log.e("Error",""+e);
e.printStackTrace();
} catch (JSONException js) {
js.printStackTrace();
}
HttpResponse response = null;
try {
response = client.execute(post);
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e("ClientProtocol",""+e);
} catch (IOException e) {
e.printStackTrace();
Log.e("IO",""+e);
}
HttpEntity entity = response.getEntity();
if (entity != null) {
try {
entity.consumeContent();
} catch (IOException e) {
Log.e("IO E",""+e);
e.printStackTrace();
}
}
Toast.makeText(this, "Your post was successfully uploaded", Toast.LENGTH_LONG).show();
}
HTTP POST request example using Apache HttpClient v.4.x
HttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("param1", param1Value, ContentType.TEXT_PLAIN);
builder.addTextBody("param2", param2Value, ContentType.TEXT_PLAIN);
HttpEntity multipart = builder.build();
httpPost.setEntity(multipart);
HttpResponse response = httpClient.execute(httpMethod);
http://httpunit.sourceforge.net/doc/cookbook.html
use PostMethodWebRequest and setParameter method
shows a very simple exapmle where you do post from Html page, servlet processes it and sends a text response..
http://java.sun.com/developer/onlineTraining/Programming/BasicJava1/servlet.html

Categories

Resources