HttpUrlConnection connection reset error when sending second message - java

Basically that's all, the first message sent is correctly received by the server, but all the next ones fail. This is the main loop that iterates over the messages and treates some errors for debugging and logic of the code. The variable udc is my database connection, but it works fine so ignore it.
for (MessageOutModel message : messageOutModels) {
HttpURLConnection connection = MakeConnection();
Date currentMoment = new Date(Calendar.getInstance().getTimeInMillis());
System.out.println("Sent message id: " + message.id);
OutputStreamWriter out = new OutputStreamWriter(
connection.getOutputStream());
out.write(message.contenido);
out.close();
//os.write(message.contenido);
System.out.println("Message sent");
int responseCode = connection.getResponseCode();
System.out.println("Connection message: " + responseCode);
message.f_ultimo_intento = currentMoment;
if (responseCode != 200) {
message.intentos++;
message.desc_error = "Connection error: " + responseCode
+ " Connection error message: " + connection.getResponseMessage() + "Response error:" +
connection.getResponseMessage();
udc.UpdateMessageOut(message);
if (message.intentos == configModel.n_reintentos) {
udc.InsertError("MAX_INTENTOS", "Se ha alcanzado el máximo número de " + "intentos para el id-ticket: " + message.id + "-" + message.ticket_number);
}
} else {
message.desc_error = "";
udc.UpdateMessageOut(message);
}
connection.disconnect();
}
There goes the method MakeConnection()
protected HttpURLConnection MakeConnection() throws IOException {
QName q = new QName(SERVER_URL, "");
URL url = new URL(q.getNamespaceURI() + q.getLocalPart());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestProperty("UserName", Username);
connection.setRequestProperty("PassWord", Password);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", MediaType.TEXT_PLAIN);
return connection;
}
Connection reset error

Use this as a quick solution.
HttpURLConnection connection = MakeConnection();
for (MessageOutModel message : messageOutModels) {
// logic from your sample
}
connection.disconnect();
Also, you can use try-with-resources to improve design a little.

At the end it resulted to be a firewall problem with the client and the server. It was blocking the connection for every other time after the first one.

Related

Error in send push notifications programmatically using java code in One Signal to android app

I have try the below code from One Signal documentation to send push notifications to mobile. But somehow it failed and throw exception.The relevant API key has been changed. I try to debug on Android studio and the error exist at " OutputStream outputStream = con.getOutputStream();" , is that possible i can customize the push notifications programmatically using these java code, Please advise.
try {
String jsonResponse;
URL url = new URL("https://onesignal.com/api/v1/notifications");
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setUseCaches(false);
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setRequestProperty("Authorization", "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj");
con.setRequestMethod("POST");
String strJsonBody = "{"
+ "\"app_id\": \"5eb5a37e-b458-11e3-ac11-000c2940e62c\","
+ "\"included_segments\": [\"All\"],"
+ "\"data\": {\"foo\": \"bar\"},"
+ "\"contents\": {\"en\": \"English Message\"}"
+ "}";
System.out.println("strJsonBody:\n" + strJsonBody);
byte[] sendBytes = strJsonBody.getBytes("UTF-8");
con.setFixedLengthStreamingMode(sendBytes.length);
OutputStream outputStream = con.getOutputStream();
outputStream.write(sendBytes);
int httpResponse = con.getResponseCode();
System.out.println("httpResponse: " + httpResponse);
if ( httpResponse >= HttpURLConnection.HTTP_OK
&& httpResponse < HttpURLConnection.HTTP_BAD_REQUEST) {
Scanner scanner = new Scanner(con.getInputStream(), "UTF-8");
jsonResponse = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
scanner.close();
}
else {
Scanner scanner = new Scanner(con.getErrorStream(), "UTF-8");
jsonResponse = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
scanner.close();
}
System.out.println("jsonResponse:\n" + jsonResponse);
} catch(Throwable t) {
t.printStackTrace();
}

Java server side connection with firebase connection timeout

I am trying to connect to firebase to send push notification to an android app.
I have written following code in Java Server side. But I am getting connection timed out exception always.
final String apiKey="AAAAeEpqP-w:APA91bFulyT23Km-onTNr_q5yEz4uoOaM8KdE4LMyIoz6kWlk3pJSHirDJBSiqESRXKiGa-Z_tBfpXA6naaaTXxcFFxAnaSkMTPVVOMswyJ0bhhdpwlo-92HXgxRMsHV6Y8bNaHX7tMd";
int i=0;
try {
URL url = new URL("https://fcm.googleapis.com/fcm/send");
HttpsURLConnection conn = (HttpsURLConnection ) url.openConnection();
System.out.println("after connection open");
//conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "key=" + apiKey);
conn.setDoOutput(true);
JSONObject json = new JSONObject();
json.put("to", "device-token");
JSONObject info = new JSONObject();
info.put("title", "notification title"); // Notification title
info.put("body", "message body");
json.put("notification", info);
OutputStreamWriter wr = new OutputStreamWriter(
conn.getOutputStream());
wr.write(json.toString());
wr.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
// result = CommonConstants.SUCCESS;
System.out.println("after closed out put stream");
int responseCode = conn.getResponseCode();
// System.out.println("Post parameters : " + input);
System.out.println("Response Code : " + responseCode);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
}
It always shows session timeout error.
Is it a correct way to send notifications to app.
Any help is appreciated.
EDIT :- I have called the same url with device token and other things from rest client and it works well.I got a notification in my app.But when i send it thru Java code at that time it shows connection timed out.
Here's the official Firebase documentation which can help you set up the server. https://firebase.google.com/docs/cloud-messaging/server
In your code I noticed json.put("to", "device-token"); and I am assuming that you are using it as a placeholder only for the example. If not, in your request you need to send a device-token like { "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..." } .

Posting data from Java and receiving in node.js applicaiton

I have written a demo in Java that posts data once a second:
public static void main(String[] arystrArgs) {
//Get Operating System name and version
String strOSname = System.getProperty("os.name").toLowerCase();
//Display application title and what it is running on
System.out.println("Java Data Posting Demo");
System.out.println("Build date: " + BUILD_DATE + ", Version: " + VERSION_NO);
System.out.println("Running on: " + strOSname.substring(0, 1).toUpperCase()
+ strOSname.substring(1).toLowerCase());
//Post data to server
HttpURLConnection conn = null;
while( true ) {
try {
Thread.sleep(DELAY_BETWEEN_POSTS);
URL url = new URL("http://localhost:8080");
conn = (HttpURLConnection)url.openConnection();
if ( conn != null ) {
//Whatever you wants to post...
String strPostData = "p1=Hello&p2=" + (new Date()).getTime();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-length", Integer.toString(strPostData.length()));
conn.setRequestProperty("Content-Language", "en-GB");
conn.setRequestProperty("charset", "utf-8");
conn.setUseCaches(false);
conn.setDoOutput(true);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(strPostData);
dos.close();
System.out.println("Post to: " + url.toString() + ", data: " + strPostData);
}
} catch (InterruptedException|IOException ex) {
//ex.printStackTrace();
} finally {
if ( conn != null ) {
conn.disconnect();
conn = null;
}
}
}
}
I have written a Node.js application that listens on port 8080, but I don't see any POST requests in the http handler, I only see GET requests when I use a browser on the same address and port to test.
Snippet from node.js application:
function defaultHandler(request, response) {
try{
if ( request.method == "POST" ) {
var strBody = "";
request.on("data", function(chunk) {
strBody += chunk;
});
request.on("end", function() {
console.log("Received posted data: " + strBody);
});
} else {
console.dir(request);
}
} catch( ex ) {
console.dir(ex);
}
};
var app = http.createServer(defaultHandler);
app.listen(8080);
This is a cut down version, but all I ever see is get requests. I can see that the Java is connecting and posting data, as when I start Node.js and only when I start Node.js, the Java application connects to the URL then starts POSTING with a second delay between posts, it I terminate node, then it stops posting and restarting node causes the posts to resume.
Your Node app never send response to client. You send a lot of request but Java Client never receive response from server. You should execute end method on response.
var http = require('http');
function defaultHandler(request, response) {
try {
if (request.method == "POST") {
var strBody = "";
request.on("data", function(chunk) {
strBody += chunk;
});
request.on("end", function() {
console.log("Received posted data: " + strBody);
});
} else {
console.dir(request);
}
respone.end(); // for example here
} catch (ex) {
console.dir(ex);
}
};
var app = http.createServer(defaultHandler);
app.listen(8080);
Here you can find documentation - https://nodejs.org/api/http.html#http_class_http_serverresponse
I'm not a Java developer, but I think you can try use flush and getResponseCode method on connection.
conn.setDoOutput(true);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(strPostData);
dos.flush();
dos.close();
int responseCode = conn.getResponseCode();
Fixed, it was the Java, I modified the Java code as follows:
URL url = new URL("http://localhost:8080");
conn = (HttpURLConnection)url.openConnection();
if ( conn != null ) {
//Whatever you wants to post...
String strPostData = "p1=Hello&p2=" + (new Date()).getTime();
conn.setRequestMethod("POST");
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept-Language", "en-GB,en;q=0.5");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-length", Integer.toString(strPostData.length()));
conn.setRequestProperty("Content-Language", "en-GB");
conn.setRequestProperty("charset", "utf-8");
conn.setUseCaches(false);
conn.setDoOutput(true);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(strPostData);
dos.flush();
dos.close();
int intResponse = conn.getResponseCode();
System.out.println("\nSending 'POST' to " + url.toString() +
", data: " + strPostData + ", rc: " + intResponse);;
}

getting Blank response from php server while access from other country in android

I made a andoid application in which I am getting response from php server, requesting in POST format. I am using below code for http connection:
// random string as boundary for multi-part http post
String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
String endLine = "\r\n";
OutputStream os;
String url = encodeUrl(methodType, graphURL, params);
Log.d("url - ",url);
Log.d("Method Type - ", methodType + " URL - " + url);
HttpURLConnection conn = (HttpURLConnection) new URL(url)
.openConnection();
conn.setConnectTimeout(60000);
conn.setReadTimeout(30000);
conn.setRequestProperty("User-Agent", System.getProperties()
.getProperty("http.agent"));
if (!methodType.equals("GET")) {
Bundle dataparams = new Bundle();
for (String key : params.keySet()) {
if (params.getByteArray(key) != null) {
dataparams.putByteArray(key, params.getByteArray(key));
}
}
// use method override
if (!params.containsKey("method")) {
params.putString("method", methodType);
}
if (params.containsKey("access_token")) {
#SuppressWarnings("deprecation")
String decoded_token = URLDecoder.decode(params
.getString("access_token"));
params.putString("access_token", decoded_token);
}
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + strBoundary);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.connect();
os = new BufferedOutputStream(conn.getOutputStream());
os.write(("--" + strBoundary + endLine).getBytes());
os.write((encodePostBody(params, strBoundary)).getBytes());
os.write((endLine + "--" + strBoundary + endLine).getBytes());
if (!dataparams.isEmpty()) {
for (String key : dataparams.keySet()) {
os.write(("Content-Disposition: form-data; filename=\""
+ key + "\"" + endLine).getBytes());
os
.write(("Content-Type: content/unknown" + endLine + endLine)
.getBytes());
os.write(dataparams.getByteArray(key));
os.write((endLine + "--" + strBoundary + endLine)
.getBytes());
}
}
os.flush();
}
String response = "";
try {
response = parseXmlSvn(conn.getInputStream());
} catch (FileNotFoundException e) {
// Error Stream contains JSON that we can parse to a FB error
//response = read(conn.getErrorStream());
Log.i("RESPONSE",""+response);
}
Log.i("RESPONSE", ""+response);
return response;
Everything is working fine on my demo server, I uploaded my PHP service to clients server. I am getting proper response from his server also.
But when client access app in 3G or 4G in some other country in his android devices, he is getting Blank response while the same service of same server can be accessible in iOS code easily by him. Is it some packet loss while getting response or any other problem?
I would really appreciate any help you can give me.
Thanks

Add a proxy for URl

How do add proxy to access a url in java? For aceessing a url I have written a java program which will tell me wether the URl is accessible or not. But it is not working a giving me response code as 404 though the Url is accessible from the browser.
Please help.
This is my code
HttpURLConnection httpURLConnection;
StringBuffer strbufstatus = new StringBuffer();
try {
//Connecting to the url
targetURL = new URL(url);
start = System.currentTimeMillis();
httpURLConnection = (HttpURLConnection) targetURL.openConnection();
httpURLConnection.setUseCaches(false);
httpURLConnection.setAllowUserInteraction(false);
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestMethod("GET");
httpURLConnection.connect();
//Getting the respond Code
int responseCode = httpURLConnection.getResponseCode();
strbufstatus.append("Response Code===> " + responseCode + "<br>");
if(responseCode==200){
// System.out.println("respondcode===> " + responseCode);
end = System.currentTimeMillis();
//Calculating the response time
difference = (end - start);
difference = difference / 1000;
// System.out.println("Response Time===> " + difference);
strbufstatus.append("Rsponse time===> " + difference + "<br>");
}
} catch (IOException ex) {
if (ex.toString().contains("java.net.UnknownHostException:")) {
strbufstatus.append(" - UnknownHostException has occured during Httpconnection\n");
} else if (ex.toString().contains("java.net.MalformedURLException: unknown protocol:")) {
strbufstatus.append(" - Unknown Protocol\n");
} else if (ex.toString().contains("java.net.ConnectException: Connection timed out: connect")) {
strbufstatus.append("Connection TimedOut\n");
} else {
strbufstatus.append("IOException has occured during Httpconnection \n");
}
ex.printStackTrace();
}
System.out.println("Status" +strbufstatus);
return strbufstatus.toString();
}
Look for specific java System.setProperty's for controlling proxy usage. Some pertinent key names are 'deployment.proxy.type' as well as others listed here.
Old but still working method is like below:
System.getProperties().put("http.proxySet", "true");
System.getProperties().put("http.proxyHost", "proxyHostname");
System.getProperties().put("http.proxyPort", "proxyPort");
System.getProperties().put("http.proxyUser", username);
System.getProperties().put("http.proxyPassword", password);

Categories

Resources