getting error in HTTPURLConnection while running program on linux server - java

I am running a progrom which is successfully running on my local machine(Success 200 Ok) but when I upload this to my linux web server I am getting the 404 error code.
My Code Is:
try{
String url = "http://sms.bazaardekho.com/ComposeSMS.aspx";
String charset = "UTF-8";
String username = "shaillu";
String priority="1";
String dnd="1";
String unicode="0";
String query = String.format("username=%s&priority=%s&dnd=%s&unicode=%s",
URLEncoder.encode(username, charset),
URLEncoder.encode(priority, charset),
URLEncoder.encode(dnd, charset),
URLEncoder.encode(unicode, charset));
URL oracle = new URL(url + "?" + query);
HttpURLConnection yc =(HttpURLConnection) oracle.openConnection();
yc.setRequestMethod("GET");
yc.setConnectTimeout(3000);
yc.setRequestProperty("Accept", "*/*");
yc.setRequestProperty("User-Agent", "PARSHWA WEB SOLUTIONS");
yc.setRequestProperty("Accept-Charset", charset);
out.println(yc.getRequestMethod());
out.println(yc.getResponseCode());
out.println(yc.getResponseMessage());
out.println("<br/>ErrorStream :"+yc.getErrorStream());
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
out.println(inputLine);
in.close();
}catch(Exception e){out.println("Exception:" + e);}
Output:
GET 404 Not Found
ErrorStream :sun.net.www.protocol.http.HttpURLConnection$HttpInputStream#33a719 Exception:java.io.FileNotFoundException: http://sms.bazaardekho.com/ComposeSMS.aspx?username=shaillu&priority=1&dnd=1&unicode=0
This program is successfully running on my local machine but when I am trying to run this on my online server to use for my website, then I am getting this error.
Please give me the cause of this error & how can I resolve this.
Thank You.

You sure on your loal and presumably windows HttpURLConnection refers to thsi class only sun.net.www.protocol.http.HttpURLConnection
On linux its defaulting to the JDL provided class I beleive. A system wide property set smewhere or eclipse doing that for you :)

Can you please try changing this
yc.setRequestProperty("User-Agent", "PARSHWA WEB SOLUTIONS");
to
yc.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) ");

Related

How to get user machine IP using Java

I am trying to get users machine ipAddress using java from my server.
I used the following code, and it works fine in local.
URL url = new URL("http://www.geoplugin.net/json.gp?jsoncallback=?");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
}
}
Using this class, response shows the ip in my local web app.(localhost:8080/myApp/getIp)
I deployed this war to my AWS server, and tried to run the servlet. But this always shows the AWS ip address only. (myIp:8080/myApp/getIp)
It doesn't shows my machine IP.
What was mistake in my code, can someone assist in this?
ServletRequest.getRemoteAddr() OR
getRemoteHost() and getRemotePort()
should returns details of the actual client
If you wanna get client ip i.e. user accessing your web-app through browser, then you can use (client-side-script)javascript to do so. Below is simple example for the same.
function show(response) {
console.log(response);
var html = 'Something went wrong !';
if (200 == response.geoplugin_status) {
html = 'Got your ip as: ' + response.geoplugin_request;
}
document.getElementById('ip').innerHTML = html;
}
var script = document.createElement('script');
script.async = true;
script.src = 'http://www.geoplugin.net/json.gp?jsoncallback=show';
document.getElementById('ip').appendChild(script);
<div id='ip'>Fetching IP ...</div>

java.io.FileNotFoundException: When using real server

I am beginner in Java and Android Studio. I have written a code by Android Studio and Wamp as server and Genymotion as simulator. all codes work fine and I can interact with mysql by use of my .php files
Then I decide to transfer codes to real server.
but I get this error:
java.io.FileNotFoundException: http://burj.1shahrvand.com/Burj/BikerLogin.php
The File is available check it here but I get Exception that file not found
The code is like this:
String uri = rp.getUri();
if(rp.getMethod().equals("GET")){
uri += "?" + rp.getEncodedParams();
}
HttpURLConnection connection;
try {
URL url = new URL(uri);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(rp.getMethod());
if (rp.getMethod().equals("POST")){
connection.setDoOutput(true);
connection.setDoInput(true);
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(rp.getEncodedParams());
writer.flush();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line);
}
return sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
Log.i("HESAM Original", e.getMessage());
e.printStackTrace();
}
return null;
I appreciate your Help!
You will get a FileNotFoundException if you call getInputStream after the server has responded withe a 404 or 410 status code.
If you want to avoid the exception, check that the response status code is a 2xx code. If it isn't then use getErrorStream instead of getInputStream.
In my case, There is an option in my Cpanel. It is MOD Security, Just turn it off, after 15 minutes my app worked properly.
Simply you need to add the port name(:8080) with the localhost ip address in URL String, like i did:
String login_url = "http://192.168.0.136:8080/login.php";

How to retrieve XML/RDF data from a link URL using in Java?

I have been trying to retrieve XML data from a URL and write to file on disk http://dbpedia.org/data/Berlin.rdf using the following code snippet.
URL urlObj = new URL("http://dbpedia.org/data/Berlin.rdf");
java.net.HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();
InputStream reader = new BufferedInputStream(connection.getInputStream());
BufferedReader breader = new BufferedReader(new InputStreamReader(reader));
String line;
BufferedWriter writer = new BufferedWriter(new eWriter("resource.xml"));
while ((line = breader.readLine()) != null) {
// writes the line to the output file
writer.write(line);
System.out.println(line);
}
writer.close();
connection.disconnect();
But I get this error: Exception in thread "main" java.io.IOException: Server returned HTTP response code: 502 for URL: http://dbpedia.org/data/Berlin.rdf
What is wrong ? How to fix this ? Thanks in advance.
A 502 HTTP Error is a Server Error.
If you go to the site (http://dbpedia.org/data/Berlin.rdf), you will see that dbpedia is currently undergoing maintenance. Go back in a couple of hours and try again and your code should work fine.
Update: It's working fine now.

Android- Java.io.Exception: content Length error Expected x amount of memeory got y amount

I've been trying to query NCBI blast website using Android and BioJava. I'm using Eclipse with the Android emulator. When I run the code as an Android app I get the following errors:
W/System.err(533): java.io.IOException: An error occured submiting sequence to BLAST server. Cause: content-length promised 2000 bytes, but received 214
When I take the very same code and run it as a regular Java app it works perfectly. Any ideas on what it might be?
It also occured to me while I was trying to make a POST request in Android . If you set Content-Length in headers and the actual content has a different length, it will throw an IOException in Android (in plain JDK it worked, although it is wrong)
You can reproduce the Exception using the following code:
try {
URL oracle = new URL("http://oasth.gr/tools/lineTimes.php");
HttpURLConnection yc = (HttpURLConnection) oracle.openConnection();
yc.setRequestProperty("User-Agent",
"Mozilla/5.0 (X11; Linux i686; rv:2.0b12) Gecko/20110222 Firefox/4.0b12");
yc.setRequestProperty("Referer",
"http://oasth.gr/tools/lineTimes.php");
yc.setRequestProperty("Accept-Language",
"el-gr,el;q=0.8,en-us;q=0.5,en;q=0.3");
yc.setRequestProperty("Accept-Charset",
"ISO-8859-7,utf-8;q=0.7,*;q=0.7");
// content length should be 29 !!
yc.setRequestProperty("Content-Length", "1000");
// content length is 29 !
String parames = "bline=63&goes=a&lineStops=886";
yc.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(yc.getOutputStream());
wr.write(parames);
wr.flush();
Log.d(TAG, "" + yc.getResponseCode());
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine;
StringBuilder sbu = new StringBuilder();
while ((inputLine = in.readLine()) != null)
sbu.append(inputLine);
wr.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
Log.e("getLinesArrival Exception", e.getMessage());
}
so if you remove line
yc.setRequestProperty("Content-Length", "1000");
it will work!

Why I'm getting 21004 as status value in reply from apple's sandbox server testing auto-renewable subscriptions?

I'm testing aut-renewable subscription but apple's sandbox server always returns status=21004, which means 'The shared secret you provided does not match the shared secret on file for your account.'.
I test with a java server, which does mostly this:
String receiptData = "theReceiptDataBytesBase64encoded";
String sharedSecret = "theSharedSecretAsPureStringProvidedByItunesconnect";
String jsonData = "{" +
"\"receipt-data\" : \"" + receiptData + "\"," +
"\"passsword\" : \"" + sharedSecret + "\"" +
"}";
URL url = new URL("https://sandbox.itunes.apple.com/verifyReceipt");
HttpURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(jsonData);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while((line = rd.readLine()) != null)
{
System.out.println(line);
}
wr.close();
rd.close();
As I tried to clear up by variable values in code sample above, I didn't encode the shared secret, using it as a plain string. Is this the problem?
Those are days that make you feel so great to be a developer ...
Looking carefully at my question above you'll see that I used the JSON key passsword with 3 friggin' s characters !!! That was the reason for a 5 hour try-and-error experience with several test products and test users and new shared secrets in the app store sandbox.
Special thanks to the iTunes team for giving the 'wrong shared secret'-message instead of the 'what the heck is the passsword key'-message.

Categories