I'm using the HttpURLConnection class to make http requests.
My code looks something like this-
while(true){
try{
connection=(HttpURLConnection)url.openConnection();
connection.setDoOutput(true);
connection.setConnectTimeout(2*1000);
InputStream in=connection.getInputStream();
}
catch(SocketTimeOutException e){}
catch(IOException e){}
}
I do some processing on the data once I retrieve the InputStream object. My problem is that if I let the program run long enough, the call to getInputStream blocks and I never get past that.
Am I missing something? Any pointers or help would be greatly appreciated. Thanks.
Set the read time out for the connection.
Also, close the streams in a finally block once you're done with them.
You should close connections that are not used. Here is example:
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setReadTimeout(2*1000);
connection.connect();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
stringBuilder.append(line + "\n");
}
String result = stringBuilder.toString();
reader.close();
Related
I am trying to build an android app for a website and I need to post some value to this page first.
Here is my code:
private void sendPOST(String user,String pass) throws IOException {
String POST_PARAMS = "username="+user+"&password="+pass;
URL obj = new URL("http://xx.xx.xx.xx/mysite/test.php");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
//----------------------------------------------------------- For POST only - START---------------------------------------------
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
// ------------------------------------------------------------For POST only - END----------------------------------------------------
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
Toast.makeText(getApplicationContext(), response.toString()==""?"No Result":response.toString(), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),"POST request failed", Toast.LENGTH_LONG).show();
}
}
when this line is executed OutputStream os = con.getOutputStream();
a null exception occurs.
I am unable to proceed further. Please suggest what i must do to remove this exception.
put your delevelopment server in another locatation other than localhost (try using the real IP, something like: 192.168.0.1).
sometimes you will receive a successfull connection from HttpUrlConnection.openConnection() (it returns non null object) and this not guarantee the subsequents calls to success. In other words, when you call con.getOutputStream() it throws an exception no matter if con is non-null.
It's the old question but I might have to answer on it because I have face to it today. When you ping http (instead https) have to put in manifest -> application: android:usesCleartextTraffic="true"
I think this would helped you years ago...
try(OutputStream os = con.getOutputStream()) {
byte[] input = POST_PARAMS.getBytes("utf-8");
os.write(input, 0, input.length);
}
maybe you should try to "connect" first before doing anything with your created HttpURLConnection con.
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.connect();
do more stuff with con...
I hope this helps you :)
URL obj = new URL("http://xx.xx.xx.xx/mysite/test.php");
URL Class object "obj" can't reach to your mentioned URL properly.
Try this instead:
URL obj = new URL("http://"+"xx.xx.xx.xx/mysite/test.php");
I am having some difficulty receiving the JSON list response from a given URL in my Android application. I am not sure if I am missing a step in firing the GET call, or the problem is on the web service side. Right when the code gets to the "getInputStream" line, it crashes
if (url != null) {
try {
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
BufferedReader in = new BufferedReader(
new InputStreamReader(httpURLConnection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
}
catch (IOException e) {
e.printStackTrace();
}
}
The errors given are as follows have to do with NetworkOnMainThread Exceptions as well as a few others. Note: This is within a method that is called in the "onCreate" method, which could also be a source of the problem.
Alright it ended up being the last issue, thanks for the clarification Daniel. I got lazy and did not put it in an ASyncTask. Works great now, thanks!
so I'm trying to do a GET Request to my web service, and since I saw that the HttpGet class is being deprecated, I try to use the HttpURLConnection class instead, and I used it successfully with a 'POST' method... however when I try to do a simple 'GET' request - I get a 405 error (bad method).
I tested the link in DHC, and the link is fine.
Here's my method:
public JSONObject getClientByDeviceId (String link) {
try {
URL url = new URL(link);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// conn.setRequestMethod("GET");
// conn.setDoOutput(true);
// conn.setDoInput(true);
// conn.setUseCaches(false);
// conn.setAllowUserInteraction(false);
// conn.setRequestProperty("Content-Type", "application/json");
OutputStream outputStream = conn.getOutputStream();
outputStream.close();
if (conn.getResponseCode() != 200) {
Log.e("conn", "Error code: " + conn.getResponseCode());
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
conn.disconnect();
JSONObject returnedObject = new JSONObject(sb.toString());
if (returnedObject != null) {
Log.e("conn", "If 400, this is the object gained: " + returnedObject.getString("Message"));
} else {
Log.e("conn", "didn't get any JSON object");
}
conn.disconnect();
return returnedObject;
}
else {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
Log.e("conn", "GREAT SUCCESS !!: " + conn.getResponseCode());
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
conn.disconnect();
JSONObject returnedObject = new JSONObject(sb.toString());
return returnedObject;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
Normally I would say that this problem is caused by trying to do a 'GET' request in a 'POST' URL. But without the two HttpGet and HttpPost classes I don't really know where to turn, all the properties that are commented out are like that because I tried them in the POST request and now I deleted one by one to try to get the method to work.
Any ideas ? or reference to an updated guide on how to properly use that HttpURLConnection class, since I couldn't find one.
Thanks in advance !
Solved it, apparently this code needed to be removed:
OutputStream outputStream = conn.getOutputStream();
outputStream.close();
I guess it was because I gave a GET URL and put that outputStream in my code and that caused the issues.
I still however don't understand why I got the "405: method GET not allowed" whereas I think I should have gotten the opposite: "POST" not allowed...
Anyway that is my solution, thanks a lot for your help guys !
HTTP 405 is caused by bad method call (Method not Allowed). That means you called GET method on POST request or vice-versa. You should add handling for you GET method on your Web-Service to get it working.
For anyone still reaching here from a search engine, my solution was similar -
I removed the line "conn.setDoOutput(true);" (or set it to false)
i'm looking for tutorial or quick example, how i can send POST data throw openStream.
My code is:
URL url = new URL("http://localhost:8080/test");
InputStream response = url.openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(response, "UTF-8"));
Could you help me ?
URL url = new URL(urlSpec);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(method);
connection.setDoOutput(true);
connection.setDoInput(true);
// important: get output stream before input stream
OutputStream out = connection.getOutputStream();
out.write(content);
out.close();
// now you can get input stream and read.
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
writer.println(line);
}
Use Apache HTTP Compoennts http://hc.apache.org/httpcomponents-client-ga/
tutorial: http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html
Look for HttpPost - there are some examples of sending dynamic data, text, files and form data.
Apache HTTP Components in particular, the Client would be the best way to go.
It absracts a lot of that nasty coding you would normally have to do by hand
I'm making an http GET request. It works in about 70% of my attempts. For some reason, I sometimes get no response string from a successful connection. I just setup a button in my app which keeps firing the code below. One call might fail to reply with a string, the next call works fine:
private onButtonClick() {
try {
doit();
} catch (Exception ex) {
...
}
}
public void doit() throws Exception {
URL url = new URL("http://www.example.com/service");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setAllowUserInteraction(false);
connection.setReadTimeout(30 * 1000);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Authorization",
"Basic " + Base64.encode("username" + ":" + "password"));
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = "";
StringBuilder sb = new StringBuilder();
while ((line = in.readLine()) != null) {
sb.append(line);
}
in.close();
connection.disconnect();
// Every so often this prints an empty string!
System.out.println(sb.toString());
}
am I doing something wrong here? It seems like maybe I'm not closing the connection properly from the last call somehow and the response gets mangled or something? I am also calling doit() from multiple threads simultaneously, but I thought the contents of the method are thread-safe, same behavior though,
Thanks
Thanks
That method looks fine. It's reentrant, so calls shouldn't interfere with each other. It's probably a server issue, either deliberate throttling or just a bug.
EDIT: You can check the status code with getResponseCode.
For checking ResponseCode:
BufferedReader responseStream;
if (((HttpURLConnection) connection).getResponseCode() == 200) {
responseStream = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
} else {
responseStream = new BufferedReader(new InputStreamReader(((HttpURLConnection) connection).getErrorStream(), "UTF-8"));
}
For empty content resposneCode is 204. So if u can get empty body just add one more "if" with 204 code.
We also came across with the similar scenario, I came across the following solution for this issue:
- Setting up a user agent string on URLConnection object.
URLConnection conn = url.openConnection();
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 4.01; Windows NT)");
more details