Download URL in Android - java

I've tried to download HTML content from the URL http://google.com and another URL.
I tried:
URL url = new URL("http://google.com/");
urlConnection = (HttpURLConnection) url.openConnection();
And although I've tried InputStream, it didn't work the same.
try {
URL url = new URL("http://google.com/");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
System.out.print(urlConnection.getResponseCode());
}
catch (Exception e)
{
System.out.print("Error: "+e.getMessage());
}
finally {
urlConnection.disconnect();
}
At the end I see the catch and the e.getMessage is null. If I debug it, urlConnection.getResponseCode() is returning -1.

You set DoOutput where you will not do output. You do not set DoInput where you do input. Remove the chunked streaming mode.

Related

Switch to POST method in java doesn't work

I can't understand how to switch to POST method in my HttpsURLConnection. On the debugger the request method is GET also after the setRequestMethod method. Can you tell me where is my mistake?
try {
URL url=new URL("https://smartmates.herokuapp.com");
HttpsURLConnection connection= (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
//I'll add some params here
connection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Thank you very much.
This is a piece of code that I use to POST the String mensaje and receiving rta.ToString(). I think that DoSetInput(true) is a mistake, because you want to send a POST (output) and, eventually, get a response.
`
String urlParametros = "<?xml version=\"1.0\"?>";
urlParametros = urlParametros + mensaje;
byte[] postDatos = urlParametros.getBytes(StandardCharsets.UTF_8);
try {
URL miurl = new URL(url);
con = (HttpURLConnection) miurl.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
//******…………..
con.setRequestProperty("User-Agent", "Java client");
con.setRequestProperty("Content-Type", "text/xml");
try (DataOutputStream datos = new DataOutputStream(con.getOutputStream())) {
datos.write(postDatos);
}
StringBuilder rta;
try (BufferedReader entrada = new BufferedReader(
new InputStreamReader(con.getInputStream()))) {
String linea;
rta = new StringBuilder();
while ((linea = entrada.readLine()) != null) {
rta.append(linea);
rta.append(System.lineSeparator());
}
}
return rta.toString();
} finally {
con.disconnect();
}´
Hope it helps
Daniel

unexcepted end of stream on Connection

I am doing a Android app and trying to input a new data into the student database, the connection which is HttpURLConnection is ok. I got a problem which says: java.io.IOException: unexcepted end of stream on Connection {....(here is my host address}.
I think the main problem is the conn.getOutputStream(), and I have check that the stream is not closed.
public static void createUser(Student user){
//initialise
URL url = null;
HttpURLConnection conn = null;
final String methodPath="/friendfinder.student/";
try {
Gson gson =new Gson();
String stringUserJson=gson.toJson(user);
url = new URL(BASE_URI + methodPath);
//open the connection
conn = (HttpURLConnection) url.openConnection();
//set the timeout
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
//set the connection method to POST
conn.setRequestMethod("POST");
//set the output to true
conn.setDoOutput(true);
//set length of the data you want to send
conn.setFixedLengthStreamingMode(stringUserJson.getBytes().length);
//add HTTP headers
conn.setRequestProperty("Content-Type", "application/json");
//Send the POST out
PrintWriter out= new PrintWriter(conn.getOutputStream());
out.print(stringUserJson);
out.close();
Log.i("error",new Integer(conn.getResponseCode()).toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
conn.disconnect();
}
}
Would someone take a look at my code and give me a suggestion please?

HTTP URL redirect status code

The url which I give gets redirected. When i hit the url with some browser it redirects to another site. When i test it in some rest client i am getting http code 302, which is correct for redirect. But i try the same with below code, it returns 200. Can somebody help me out ?Thanks in advance.
updated url.
try {
URL url = new URL("https://securestore.hbo.com/cart.php?f=pplogin&ppx=1&method=checkout");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
int code = connection.getResponseCode();
System.out.println(connection.getResponseMessage());
System.out.println("code is" + code);
connection.disconnect();
}
catch (MalformedURLException e) {
e.printStacTrace();
}
catch (IOException e) {
e.printStackTrace();
}
If url1 is being redirected to url2, then you will get 302 status. However if you code is directally calling url2, you are bound to get 200.
Try the following code.
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
.....
connection = (HttpConnection)Connector.open(url);
responseCode = connection.getResponseCode();
Try adding a response with the 302 code you want. Something like connection.setStatus(statusCode) I may be wrong though.
The HttpURLConnection will follow the redirects by default.
Try setting the following if you do not wish to follow redirects:
HttpURLConnection.setFollowRedirects(false);
For example, in relation to your code:
try {
URL url = new URL("");
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
int code = connection.getResponseCode();
System.out.println(connection.getResponseMessage());
System.out.println("code is" + code);
connection.disconnect();
}
catch (MalformedURLException e) {
e.printStacTrace();
}
catch (IOException e) {
e.printStackTrace();
}

Should i use Same HttpUrlconnection or define each time a new one?

I am using HttpUrlConnect to post data to a webservice .
This posting of data will happen , whenever there is any logging event called .(so this is continous)
I have a question with respect to this , should i use the same HttpURLConnection as shown below
private HttpURLConnection getConnection() throws Exception {
URL url = new URL("http://localhost:8080/RestTest/ajax/user_info");
HttpURLConnection conn = null;
conn = (HttpURLConnection) url.openConnection();
return conn;
}
public void execute() throws Exception {
OutputStream os = null;
try {
HttpURLConnection conn = null;
conn = getConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
String input = "{\\\"qty\\\":100,\\\"name\\\":\\\"sdsfds ddd\\\"}";
os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
conn.getInputStream();
} catch (Exception e) {
e.printStackTrace();
}
finally {
if (os != null) {
os.close();
}
}
}
Or should i define connection everythime as shown below ??
public void execute() throws Exception {
OutputStream os = null;
HttpURLConnection conn = null;
try {
URL url = new URL("http://localhost:8080/RestTest/ajax/user_info");
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
String input = "{\\\"qty\\\":100,\\\"name\\\":\\\"sdsfds ddd\\\"}";
os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
conn.getInputStream();
} catch (Exception e) {
e.printStackTrace();
}
finally {
conn.disconnect();
if (os != null) {
os.close();
}
}
}
Please tell me what is appropiate in this context ??
HttpURLConnection's javadoc says:
Each HttpURLConnection instance is used to make a single request but the underlying network connection to the HTTP server may be transparently shared by other instances.
So, although in the background the connection could be the same, you should use a new intance per request.

Java http post: values arent added

I try to send post request, but webserver returns that I added no post-values. I spent a lot of time trying to solve this issue, but no result. Here is the code:
public static String post(String url, String postParams)
{
URLConnection connection = null;
try
{
connection = initializeConnection(url);
connection.setDoOutput(true);
((HttpURLConnection) connection).setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "text/xml");
connection.setRequestProperty("Accept", "text/xml");
connection.setUseCaches(false);
connection.setDoInput(true);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.write(postParams.getBytes());
wr.flush();
wr.close();
// Get Response
InputStream is = connection.getInputStream();
return inputStreamToString(is);
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
protected static HttpURLConnection initializeConnection(String stringUrl)
{
HttpURLConnection connection;
URL url = null;
try
{
url = new URL(stringUrl);
}
catch (MalformedURLException e1)
{
e1.printStackTrace();
}
try
{
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5000);
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
return connection;
}
public static String inputStreamToString(InputStream is)
{
BufferedReader r = new BufferedReader(new InputStreamReader(is));
StringBuilder total = new StringBuilder();
String line;
try
{
while ((line = r.readLine()) != null)
{
total.append(line);
}
}
catch (IOException e)
{
e.printStackTrace();
}
return total.toString();
}
I receive a message from webserver where it is told that no post-values are added. As far as I understand from the code, the values are added. I'm stuck.
It turned out that all I had to do was to replace
connection.setRequestProperty("Content-Type", "text/xml");
with
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
So simple and so much time spent to clear it out...
By the way, how could I know that server requires this header? I thought that all the work that is essential to the request would be automatically done by java..
P.S. Installing fiddler helped to solve the issue, thanks for that.
debug the 'postParams' parameter and check what been sent.

Categories

Resources