I am checking a website for 302 messages, but I keep receiving 200 in my code:
private class Checker extends AsyncTask<Integer,Void,Integer>{
protected void onPreExecute(){
super.onPreExecute();
//display progressdialog.
}
protected Integer doInBackground(Integer ...code){
try {
URL u = new URL ( "http://www.reddit.com/r/notarealurlinredditqwerty");
HttpURLConnection huc = (HttpURLConnection) u.openConnection();
huc.setRequestMethod("POST");
HttpURLConnection.setFollowRedirects(true);
huc.connect();
code[0] = huc.getResponseCode();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return code[0];
}
protected void onPostExecute(Integer result){
super.onPostExecute(result);
//dismiss progressdialog.
}
}
That is my Async task for checking. Here is the code implementing it:
int code = -1;
Checker checker = new Checker();
try {
code = checker.execute(code).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
Log.d("code:", "" + code);
That log always returns 200, but I know that URL is 302 (it redirects to a search page on reddit.com).
What am I doing wrong?
This line just needs to be set to false:
HttpURLConnection.setFollowRedirects(false);
You can use HttpURLConnection. I have used it for response code in a few applications. I did not encounter any problems.
URL url = new URL("http://yoururl.com");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int code = connection.getResponseCode();
Related
I am coming to a issue where I have a button link that goes to a pdf. I need help to check if there is no pdf (404) then do not show the button at all. If it is 200 then show the button. How can I achieve this in java? Thanks !
Here is my code:
Pay
Java
public String jobpayGrade;
public String getJobpayGrade() {
return jobpayGrade;
}
public void setJobpayGrade(String jobpayGrade) {
this.jobpayGrade = "http://WEB_ADDRESS/paygrade/" + jobpayGrade + ".pdf";
}
Here is how you can get the error code of a page
URL url = new URL(jobpayGrade);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int code = connection.getResponseCode();
if(code==200){
//set visible
}else if(code==404){
//set not visible
}
If I was implementing it it would look like this somewhat
if(isValidURLConnection(jobpayGrade)){
button.setVisible(true);
}else {
button.setVisible(false);
}
private boolean isValidURLConnection(String jobPayGrade){
URL url = null;
try {
url = new URL(jobPayGrade);
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
try {
connection.setRequestMethod("GET");
connection.connect();
return connection.getResponseCode()==200;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
I have problem with connecting to my server. Following code returns -1 as response code and null as response message.
protected Boolean doInBackground(MyTaskParams... params) {
URL url = null;
String load = params[0].jobj.toString();
try {
url = new URL(params[0].serverUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(3000);
urlConnection.setReadTimeout(3000);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
urlConnection.setChunkedStreamingMode(0);
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
OutputStreamWriter osw = new OutputStreamWriter(urlConnection.getOutputStream());
osw.write(load);
osw.flush();
osw.close();
if(urlConnection.getResponseCode()==200 && urlConnection.getResponseMessage().contains("true") ) return true;
else return false;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
While debbuging url and body content (which is load in code) are correct. When I try to connect with the server using those params with Fiddler it works perfectly and I get 200 status code. Do you have any ideas what is wrong?
Im passing jData object as the jobj:
JSONObject User=new JSONObject();
JSONObject Mobile=new JSONObject();
JSONObject jData=new JSONObject();
try {
User.put ("UserLogin", "test");
User.put ("UserPassword", "test");
Mobile.put ("MobileIDD", IDD);
Mobile.put("MobileToken", token);
jData.put("Mobile", Mobile);
jData.put("User", User);
} catch (JSONException e) {
e.printStackTrace();
}
#EDIT
Solution with System.setProperty("http.keepAlive", "false") didnt help.
I solved the problem. It was in this line:
if(urlConnection.getResponseCode()==200 && urlConnection.getResponseMessage().contains("true") ) return true;
When I changed it to:
int code = urlConnection.getResponseCode();
if (code==200.....)
It started working.
I have the following code in my program, used for inserting record -
private Void downloadUrl() throws IOException {
String postParameters;
HttpURLConnection urlConnection = null;
postParameters = "name="+ URLEncoder.encode(user.name,"UTF-8")
+"&age="+URLEncoder.encode(user.age+"","UTF-8")
+"&username="+URLEncoder.encode(user.username,"UTF-8")
+"&password="+URLEncoder.encode(user.password,"UTF-8");
if (postParameters != null) {
Log.i("Post", "POST parameters: " + postParameters);
try {
URL urlToRequest = new URL(SERVER_ADDRESS);
urlConnection = (HttpURLConnection) urlToRequest.openConnection();
urlConnection.setReadTimeout(30000 /* milliseconds */);
urlConnection.setConnectTimeout(30000 /* milliseconds */);
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
urlConnection.setFixedLengthStreamingMode(
postParameters.getBytes().length);
PrintWriter out = new PrintWriter(urlConnection.getOutputStream());
out.print(postParameters.getBytes());
out.close();
// handle issues
int statusCode = urlConnection.getResponseCode();
Log.e("Response", "The response is: " + statusCode);
} catch (MalformedURLException e) {
// handle invalid URL
Log.e("Response", "invalid URL");
} catch (SocketTimeoutException e) {
// hadle timeout
Log.e("Response", "handle timeout");
} catch (IOException e) {
// handle I/0
Log.e("Response", "handle IO problem");
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}
return null;
}
The code is showing no errors and the logged entries are
09-27 12:24:17.944 5006-5039/? E/Response﹕ The response is: 200
09-27 12:24:33.729 5006-5118/? I/Post﹕ POST parameters: name=vibha&age=25&username=vib&password=1234
But when I check the database, the new record is not created.
But if I use PHP code in a file and post the same parameters,the records are getting inserted.
My requirement for help and guidance is how to pass the post parameter in the HttpURLConnection class
I need to handle an exception when web service is not available. In my app i am requesting an web service what will return me an XML data. My app is working correctly when web service is available. But when the web service is unavailable then my app become crash.how to catch that exception in java. Please note that i am developing an app for android.
when the web service is unavailable the it looks likes the following image
with this you can check webservice available or not
public void isAvailable(){
// first check if there is a WiFi/data connection available... then:
URL url = new URL("URL HERE");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Connection", "close");
connection.setConnectTimeout(10000); // Timeout 10 seconds
connection.connect();
// If the web service is available
if (connection.getResponseCode() == 200) {
return true;
}
else return false;
}
This is how i have solved that problem with the help of Krishna's code
public static boolean isAvailable(String link){
boolean available = false;
URL url = null;
try {
url = new URL(link);
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) url.openConnection();
} catch (IOException e1) {
}
connection.setRequestProperty("Connection", "close");
connection.setConnectTimeout(100000); // Timeout 100 seconds
try {
connection.connect();
} catch (IOException e) {
}
try {
if (connection.getResponseCode() == 200) {
// return true;
available = true;
}
else
available = false;
//return false;
} catch (IOException e) {
e.printStackTrace();
}
return available;
}
In the "doInBackground" function of a AsyncTask, I got the following piece of code :
try
{
URL url = new URL(myUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
Authenticator.setDefault(new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication ("myUsername", "myPassword".toCharArray());
}
});
conn.connect();
int response = conn.getResponseCode();
inputStream = conn.getInputStream();
String content = convertInputStreamToString(inputStream);
return content;
catch (Exception e) {
e.printStackTrace();
return null;
}
When the credentials are ok, everything works fine and the ResponseCode is 200. But if I put the wrong credentials, getResponseCode() makes the AsyncTask wait for an answer indefinitely (timeout won't work). Looking at HttpUrlConnection object tells me that the ResponseCode is -1.
I need to handle every situation, even if the user provides a bad credential. How can I get an usable answer? Should I use another class than HttpUrlConnection?
Are you returning String back from this function and are you handling exceptions? Did you write onPostExecute?
Here is the code that works perfectly for me:
URL url = new URL(strUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Host", "myhost.com");
conn.setRequestProperty("Authorization", "Basic " + Base64.encodeToString(toencode, Base64.DEFAULT));
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; PPC; en-US; rv:1.3.1)");
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setConnectTimeout (5000) ;
conn.setDoOutput(true);
conn.setDoInput(true);
BufferedInputStream in = new BufferedInputStream(conn.getInputStream());
result = Utilities.readStream(in);
status_code = conn.getResponseCode();
return result;
} catch (MalformedURLException e) {
return e.getMessage();
} catch (ProtocolException e) {
try {
status_code = conn.getResponseCode();
} catch (IOException e1) {
status_code = -1;
}
return e.getMessage();
} catch (IOException e) {
try {
status_code = conn.getResponseCode();
} catch (IOException e1) {
status_code = -1;
}
return e.getMessage();
} catch ( Exception e ) {
try {
status_code = conn.getResponseCode();
} catch (IOException e1) {
status_code = -1;
}
return e.getMessage();
}
finally
{
conn = null;
}