Confusion regarding the usage of getContent() of HTTPUrlconnection in Android - java

I am trying to read HTTP response using the HTTPUrlConnection in Android.
The getcontent() method of HTTPUrlConnection says it returns "Object" representing the content. What type of object is this? It's just saying "object" which I believe is the root object. What method can I
use to extract the contents?
Also, Instead if I use getInputStream() of HTTPUrlConnection and start reading it's contents, will it give me the data staring right from the headers or from the content?
Thanks.

With getInputStream() you will receive the whole page including headers and so on.
Exaple from: http://developer.android.com/reference/java/net/HttpURLConnection.html
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();
}
}
With getContent() you get an normal Java Object thats right. I think u can cast it to a String and so get it's content.

Related

HttpURLConnection connect() , getInputStream() , getContent() , HttpGet

I use the class HttpURLConnection , but Iam confused with some methods
assume the HttpURLConnection object name is "c"
removing c.connect() will result in a success connection and it will retrieve the connection result without any problem
the output of c.getInputStream() and (InputStream) c.grtContent() are identical , so what is the difference betqween them
using HttpGet will reach the same approach as HttpURLConnection , so what is the difference between the two methods
what are the extra benefits for HttpURLConnection on URLConnection
c = (HttpURLConnection) (URL).openConnection();
c.connect(); //adding or removing makes the same result , so what is the usage of this method
InputStream stream= c.getInputStream();
InputStream stream2 = (InputStream) c.getContent();
//stream and stream2 are identical , so what is the differece between getInputStream() and getContent()
//============================
HttpGet c= new HttpGet(url);
HttpResponse response = c.execute(httpGet)
InputStream stream3 = response.getEntity().getContent();
//also stream3 is the same as stream & stream2 ; so how dose it different between HttpGet & HttpURLConnection
From Android documentation:
[HttpURLConnection is] A URLConnection with support for HTTP-specific features.
For instance, from an HttpURLConnection you can retrieve the HTTP method or the HTTP status code, which are HTTP-specific.
The URLConnection class, instead, is:
The abstract class URLConnection is the superclass of all classes that represent a communications link between the application and a URL
The normal usage is:
Create a URL object
Get a URLConnection by calling url.openConnection(). The returned object can be casted to an HttpURLConnection
get an InputStream by calling the connection.getInputStream() method
Close the connection (disconnect() method) (see #EJP comments)
Concerning the connect() method, from the Oracle documentation:
You are not always required to explicitly call the connect method to initiate the connection. Operations that depend on being connected, like getInputStream, getOutputStream, etc, will implicitly perform the connection, if necessary.
The difference between the HttpGet and HttpURLConnection is that they belong to 2 different libraries, but functionally they are more or less the same (now HttpGet has been deprecated and removed, so you won't find it in the standard Android APIs)

How to send info in body using post method in java class file

I requested to send some parameters from java file using post method. I did
String urlParameters = "param1=a&param2=b&param3=c";
URL url = new URL("http://testing/index.jsp");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(urlParameters);
writer.flush();
But from receiver's end asks me to send it in body instead of url parameter. I am not sure what I am doing wrong. Please explain me how this code will work and what changes has to be done if I want to send info in request body.
i believe you either need to call the connect() method on the URLConnection at the end, or call a method that would cause the connect to be called for you, like fetching the resulting input stream.
Also you should think about what format the body should be in. Often people like to use standard formats like json, but you will have to decide that between you and the people implementing the server.

Using HttpURLConnection to POST in Java

I've read lots and tried lots relating to HTTP POSTS using HttpURLConnection and almost everything I come across has a similar structure which starts with these 3 lines:
url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
When I try this I always get a "Connection Already Established" exception when calling setRequestMethod, which makes perfect sense as I'm clearly calling openConnection before setting the request type. Although reading the docs openConnection doesn't actually open the connection in theory.
There are several posts about this problem on SO such as this and this. I don't understand however why every piece of advice about how to write this code has these 3 lines in this order.
I'm guessing this code must work in most instances as someone must have tested it, so why doesn't this code work for me? How should I be writing this code?
I am aware these are other libraries I can use out there, I'm just wondering why this doesn't work.
Why the suspect code in the question has been duplicated all over the internet is something I can't answer. Nor can I answer why it seems to work for some people and not others. I can however answer the other question now, mainly thanks to this link that Luiggi pointed me to.
The key here is understanding the intricacies of the HttpURLConnection class. When first created the class defaults to a "GET" request method, so nothing needs to be changed in this instance. The following is rather unintuitive, but to set the request method to "POST" you should not call setRequestMethod("POST"), but rather setDoOutput(true) which implicitly sets the request method to post. Once you've done that you're good to go.
Below, I believe, is what a post method should look like. This is for posting json, but can obviously be altered for any other content type.
public static String doPostSync(final String urlToRead, final String content) throws IOException {
final String charset = "UTF-8";
// Create the connection
HttpURLConnection connection = (HttpURLConnection) new URL(urlToRead).openConnection();
// setDoOutput(true) implicitly set's the request type to POST
connection.setDoOutput(true);
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-type", "application/json");
// Write to the connection
OutputStream output = connection.getOutputStream();
output.write(content.getBytes(charset));
output.close();
// Check the error stream first, if this is null then there have been no issues with the request
InputStream inputStream = connection.getErrorStream();
if (inputStream == null)
inputStream = connection.getInputStream();
// Read everything from our stream
BufferedReader responseReader = new BufferedReader(new InputStreamReader(inputStream, charset));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = responseReader.readLine()) != null) {
response.append(inputLine);
}
responseReader.close();
return response.toString();
}
As per https://stackoverflow.com/a/3324964/436524, you need to call connection.setDoOutput(true) for it to expect a POST request.
This makes your code like this:
url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
connection.setDoOutput(true);

Sending sms via java

I am going to send sms via java. The problem is the sms gateway ask me to send in this format
http://push1.maccesssmspush.com/servlet/com.aclwireless.pushconnectivity.listen
ers.TextListener?userId=xxxxx&pass=xxxx&appid=xxxx&subappid=xxxx&msgtyp
e=1&contenttype=1&selfid=true&to=9810790590,9810549717&from=ACL&dlrre
q=true&text=This+is+a+test+msg+from+ACL&alert=
The problem how to call this from a java application is it possible or does it need special libraries? IS it using HttpURLConnection will do the job? Thank you.
A Sample code I have done below is this correct.
URL sendSms1 = new URL("http://push1.maccesssmspush.com/servlet/com.aclwireless.pushconnectivity.listen
ers.TextListener?userId=xxxxx&pass=xxxx&appid=xxxx&subappid=xxxx&msgtyp
e=1&contenttype=1&selfid=true&to=9810790590,9810549717&from=ACL&dlrre
q=true&text=This+is+a+test+msg+from+ACL&alert=");
URLConnection smsConn1 =
sendSms1.openConnection();
It's just an HTTP call, you don't need anything special in Java (or any modern language, I expect). Just build up the string as appropriate*, then make an HTTP request to that URL.
Take a peek at the Sun tutorial Reading from and Writing to a URLConnection if you need to pick up the basics of how to do the request part in Java. This uses the built-in classes, I'm sure there are dozens of libraries that handles connections in funky and/or convenient ways too, so by all means use one of those if you're familiar with it.
*One potential gotcha which might not have occurred to you - your query string arguments will have to be URL-encoded. So the + characters for example in the text parameter, are encoded spaces (which would have a different meaning in the URL). Likewise, if you wanted to send a ? character in one of your parameters, it would have to appear as %3F. Have a look at the accepted answer to HTTP URL Address Encoding in Java for an example of how you might build the URL string safely.
It looks like a simple GET request, you can use Apache HttpClient libarary for executing such a request. Have a look into a tutorial by Vogella here: http://www.vogella.de/articles/ApacheHttpClient/article.html for sample source code and explanations.
You can try to use java.net.URL library。
like this
// at this before you need to generate the urlString as "http://push1.maccesssmspush.com/servlet/com.aclwireless.pushconnectivity.listen
ers.TextListener?userId=xxxxx&pass=xxxx&appid=xxxx&subappid=xxxx&msgtyp
e=1&contenttype=1&selfid=true&to=9810790590,9810549717&from=ACL&dlrre
q=true&text=This+is+a+test+msg+from+ACL&alert="
URL url = new URL(urlString);
// send sms
URLConnection urlConnection = url.openConnection();// open the url
// and you, also can get the feedback if you want
BufferedReader br = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream()));
URL url = new URL("http://smscountry.com/SMSCwebservice.asp");
HttpURLConnection urlconnection = (HttpURLConnection) url.openConnection();
[Edit]
urlconnection.setRequestMethod("POST");
urlconnection.setRequestProperty("Content-Type","application/x-www-form-urlenc‌​oded");
urlconnection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(urlconnection.getOutputStream());
out.write(postData);
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(urlconnection.getInputStream()));
String decodedString;
while ((decodedString = in.readLine()) != null) {
retval += decodedString;
}

How do I retrieve a URL from a web site using Java?

I want to use HTTP GET and POST commands to retrieve URLs from a website and parse the HTML. How do I do this?
You can use HttpURLConnection in combination with URL.
URL url = new URL("http://example.com");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
InputStream stream = connection.getInputStream();
// read the contents using an InputStreamReader
The easiest way to do a GET is to use the built in java.net.URL. However, as mentioned, httpclient is the proper way to go, as it will allow you among others to handle redirects.
For parsing the html, you can use html parser.

Categories

Resources