Does threading work, when external applications block each other? - java

I have two raspberry pi´s uploading content to a webpage from the same router, which occasionally makes them block access for each other. To prevent this in java, you would normally use threads and synchronize, wait/notify and all that - but how can you do that, when the applications don´t know about each others excistens? -
My code looks something like that - and works otherwise as expected.
public void sendStrings(String output) {
String url2 = "http://myhomepage.com";
HttpURLConnection connection = null;
try {
URL obj = new URL(url2);
connection = (HttpURLConnection) obj.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
connection.connect();
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(output);
writer.flush();
writer.close();
InputStream input = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String otherLine;
int responseCode = connection.getResponseCode();
}
catch (IOException e) {
} finally {
connection.disconnect();
}
}

Related

Handle timeout of HttpUrlConnection

I want to do something after timeout. but my code is not doing anything and it's just keep trying to connect...
try {
URL url = new URL(p1[0]);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setConnectTimeout(5000);
con.setReadTimeout(5000);
if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream in = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader( in ));
res = br.readLine();
}
} catch (IOException e) {
Global.mkOkDialog(c, "Couldn't connect to server.");
e.printStackTrace();
}
the message above in catch block not showing at all after 5 seconds
First of all, you don' actually connect to anything, you should call con.connect(). Catch block gets executed only in case of IOException which is not happening.
With if(con.getResponseCode()==HttpURLConnection.HTTP_OK) you're checking if the HTTP-Response-Code is 200, which it is if you get an ok-response. Any other response code is not handled by your program and thus does not execute any further code.

Sending post using HttpURLConnection

I have a node.js which waits for post with 2 parameters (name and pass):
app.post('/login.html', function (req, res) {
log.info(req.body);
userName = req.body.name;
pass = req.body.pass;
...
}
I'm trying to send post with the 2 parameters via simple java application, but I can't see that it arrive to the node.js.
what am I missing ?
The java code:
public static void main(String[] args) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL("http://83.63.118.111:31011/login.html");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000);
urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
urlConnection.setConnectTimeout(10000);
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
String str = "name='root'&pass='123456'";
//System.out.print(str);
writer.write(str);
writer.flush();
Thread.sleep(100);
writer.close();
os.close();
}
Your code will close when start send data (send and stop)
You should wait it done.
Add code after writer.flush();
Example get response:
BufferedReader in = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
or just get responseCode:
int responseCode = urlConnection.getResponseCode();
Your program wait send request success or fail.
I think you use Thread.sleep(100); to wait send request, but it stop your Thread (don't send data to server)
Your code have req.body, Express.js don't have it, need use middleware body-parser.

Java Post Connection Using Try with Resources

I want to implement the code for handling POST requests using try with resources.
Following is my code:
public static String sendPostRequestDummy(String url, String queryString) {
log.info("Sending 'POST' request to URL : " + url);
log.info("Data : " + queryString);
BufferedReader in = null;
HttpURLConnection con = null;
StringBuilder response = new StringBuilder();
try{
URL obj = new URL(url);
con = (HttpURLConnection) obj.openConnection();
// add request header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("Content-Type", "application/json");
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(queryString);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
log.info("Response Code : " + responseCode);
if (responseCode >= 400)
in = new BufferedReader(new InputStreamReader(con.getErrorStream()));
else
in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
}catch(Exception e){
log.error(e.getMessage(), e);
log.error("Error during posting request");
}
finally{
closeConnectionNoException(in,con);
}
return response.toString();
}
I have the following concerns for the code:
How to introduce conditional statements in try with resources for the above scenario?
Is there a way to pass on the connection in try with resources? (It can be done using nested try-catch blocks since URL and HTTPConnection is not AutoCloseable, which itself is not a compliant solution)
Is using try with resources for the above problem is a better approach?
Try this.
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
try (AutoCloseable conc = () -> con.disconnect()) {
// add request headers
try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
wr.writeBytes(queryString);
}
int responseCode = con.getResponseCode();
try (InputStream ins = responseCode >= 400 ? con.getErrorStream() : con.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(ins))) {
// receive response
}
}
() -> con.disconnect() is a lambda expression which execute con.disconnect() at finally stage of the try statement.
1: You can use conditional statements inside try with resources statement also. Unfortunately you have to define new variable for this block and cannot use a predefined variable. ( variable in in your code)
try (BufferedReader in = (responseCode >= 400 ? new BufferedReader(new InputStreamReader(con.getErrorStream())) : new BufferedReader(new InputStreamReader(con.getInputStream())))) {
// your code for getting string data
}
2: I'm not sure HttpUrlConnection is AutoCloseable, So it might be a good idea to call the disconnect() yourself. I'm open to any suggestion on this one.
3: try with resources will definitely help you in managing the resources. But if you're confident that you're releasing the resources properly after use, then your code is fine.

HttpURLConnection returned different result on Android 5.1 and 4.4 while passing the same params

public static String request(String httpUrl, String httpArg) {
BufferedReader reader = null;
String result = "";
StringBuffer sbf = new StringBuffer();
httpUrl = httpUrl + "?" + httpArg;
try {
URL url = new URL(httpUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("apikey", myAPpiKey);
conn.connect();
if (conn.getResponseCode() == 200) {
InputStream is = conn.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead);
sbf.append("\r\n");
}
reader.close();
result = sbf.toString();
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
Above code worked well on Android 5.1 and Android 6.0, and it returned correct result that I want. But when I ran these on Android 4.4, using the same params, it returned different result. I have tried several times, and attached debugger to the process. I found that the connection could be built successfully, and the ResponseCode was also 200.
I guess there must be something wrong with the HttpURLConnection params, so that the server returned different result. Did I set the params in a way that could work on Android 5.1 and 6.0 but not on 4.4? Can anybody tell me where did I do wrong?
Try below code:
URL url = new URL(httpUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setChunkedStreamingMode(0);
conn.setDoInput(true);
conn.setRequestMethod("GET");
conn.setRequestProperty("apikey", myAPpiKey);
if (conn.getResponseCode() == 200) {
InputStream is = conn.getInputStream();
.........
}
It works for me. Hope it will work.

Unable to use GET Method

I am trying to write a code which will give me the contents of the page as the response in a string using GET method in java.
Below is the code I am using, its throwing me error that java.net.MalformedURLException: no protocol
If I try inserting http:// in starting of the URL its giving me Unknown Host Exception.
String request = ("http://gotoanswer.com/?q=What+is+the+Java+equivalent+for+the+following+in+curl%3F");
System.out.println(request);
URL url = null;
try{
new URL(request);
HttpURLConnection connection = (HttpURLConnection) new URL(request).openConnection();
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "text/xml");
connection.setRequestProperty("charset", "utf-8");
connection.connect();
Reader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
for ( int c = in.read(); c != -1; c = in.read() )
System.out.print((char)c);
}
catch(IOException e){
System.out.println(e);
}

Categories

Resources