I don't know why HttpURLConnection fails on android but succeeds in java Eclipse. I have been facing that problem for many days and trying to solve it but have never pass it. The code in my case as followings:
try {
url = "https://mobitrade.vpbs.com.vn:8080/getlistckindex/hnx";
URL urlGetSymbol = new URL(url);
HttpURLConnection con = (HttpURLConnection) urlGetSymbol.openConnection();
con.setRequestMethod("GET");
con.setReadTimeout(15000);
con.setConnectTimeout(15000);
con.setDoOutput(true);
con.connect();
int responseCode = con.getResponseCode();
BufferedReader in =new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder response = new StringBuilder();
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
String responseString = response.toString().replaceAll("\\[", "").replaceAll("\\]", "")
.replaceAll("\"", "");
} catch (IOException ioe) {
ioe.printStackTrace();
}
The code works fine in java eclipse but don't work on android due to con.connect() gets error.
I think you are using different api packages for HttpURLConnection so please check that. you can use java.net.HttpURLConnection api for the same.
Add
<uses-permission android:name="android.permission.INTERNET"/>
to your Androidmanifest.xml
Related
In my android application am reading text file which is in server.
Am using below method.
private String getUrlContents(String UrlOfFile)
{
StringBuilder content = new StringBuilder();
try
{
URL url = new URL(UrlOfFile);
URLConnection urlConnection = url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null)
{
content.append(line + "\n");
}
bufferedReader.close();
}
catch(Exception e)
{
Log.d(TAG,"Exception >>>"+Log.getStackTraceString(e));
}
return content.toString();
}
But I am getting previous value of text file. When I once do clear data of app its able to get actual value.
Please help me to solve this issue.
My problem was due to returning of cached response.
Issue solved by urlConnection.setUseCaches(false);
Thanks to all responds,
How to prevent Android from returning a cached response to my HTTP Request?
Adding header for HttpURLConnection
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!
I have implemented reCaptcha in the application I am working on. Somehow I am getting a blank reCaptcha response.
It works fine with localhost, but I am having a problem in upper environments like DEV, TEST. User response is being verified on server side (servlet).
Anyone having idea or faced similar problem ? Let me know if you need more info.
String userresponse = (String) request.getAttribute("g-recaptcha-response");
URL url = null;
HttpURLConnection conn = null;
String line, outputString = "";
try {
url = new URL(https://www.google.com/recaptcha/api/siteverify?secret=privateKey&response=userresponse);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
outputString += line;
}
Log.debug("Google response is :- "+outputString);
} catch (IOException e) {
e.printStackTrace();
}
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)