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);;
}
Related
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();
}
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.
I'm trying to send email using the SES HTTPS Query API. I have a java method that sends a GET request to an Amazon SES endpoint, I'm trying to send an email with SES and capture the result.
Code:
public static String SendElasticEmail(String timeConv,String action,String source, String destinationAddr, String subject, String body) {
try {
System.out.println("date : "+timeConv);
System.out.println("In Sending Mail Method......!!!!!");
//Construct the data
String data = "Action=" + URLEncoder.encode(action, "UTF-8");
data += "&Source=" + URLEncoder.encode(source, "UTF-8");
data += "&Destination.ToAddresses.member.1=" + URLEncoder.encode(destinationAddr, "UTF-8");
data += "&Message.Subject.Data=" + URLEncoder.encode(subject, "UTF-8");
data += "&Message.Body.Text.Data=" + URLEncoder.encode(body, "UTF-8");
//Send data
System.out.println("https://email.us-east-1.amazonaws.com?"+data);
URL url = new URL("https://email.us-east-1.amazonaws.com?"+data);
//URLConnection conn = url.openConnection();
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("x-amz-date" , timeConv);
con.setRequestProperty("Content-Length", ""+data.toString().length());
con.setRequestProperty("X-Amzn-Authorization" , authHeader);
int responseCode = ((HttpsURLConnection) con).getResponseCode();
String responseMessage = ((HttpsURLConnection) con).getResponseMessage();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
//System.out.println("Response Message : " + responseMessage);
InputStream stream = con.getInputStream();
InputStreamReader isReader = new InputStreamReader(stream );
System.out.println("hgfhfhfhgfgfghfgh");
BufferedReader br = new BufferedReader(isReader);
String result = "";
String line;
while ((line = br.readLine()) != null) {
result+= line;
}
System.out.println(result);
br.close();
con.disconnect();
}
catch(Exception e) {
e.printStackTrace();
}
return subject;
}
I have calculated the signature correctly, because on hitting from postman client getting 200 response.
URL url = new URL("https://email.us-east-1.amazonaws.com?"+data);
You missed a '/' before the question mark. It should be
URL url = new URL("https://email.us-east-1.amazonaws.com/?"+data);
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
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);