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.
Related
My program below stopped at the line:
InputStream is = conn.getInputStream();
Neither error message popped up nor any output displayed on the console.
I am running Eclipse Oxygen 4.7.0 on Red Hat Enterprise Linux Server release 7.4.
public static void solveInstance(String instanceName){
// solve a problem instance
try{
String query_url = "http://localhost:8807/scheduler";
// read Request to a JSON Object
JSONParser parser = new JSONParser();
JSONObject request = (JSONObject) parser.parse(new FileReader(instanceName));
// open connection
URL url = new URL(query_url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setDoOutput(true);
conn.setRequestMethod("POST");
// POST Request
OutputStream os = conn.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
osw.write(request.toString());
osw.close();
// Get Response
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader in = new BufferedReader(isr);
String inputLine;
StringBuffer response = new StringBuffer();
while(( inputLine = in.readLine()) != null )
{
response.append(inputLine);
}
in.close();
// Write response to a file
JSONObject jsonObj = (JSONObject) parser.parse(response.toString());
String responseFile = /path_to_result/result.json;
FileWriter fileWriter = new FileWriter(responseFile);
fileWriter.write(jsonObj.toString());
fileWriter.flush();
fileWriter.close();
System.out.println("Solved" + instanceName);
}
catch(Exception e) {
System.out.println(e);
}
}
I noticed that the similar question is asked InputStream is = httpURLConnection.getInputStream(); stop working
but it was for Android and no solution was given there.
Does anyone have some idea on that? Do not hesitate to point out anything else wrong in my code.
Thanks a lot!
Your server isn't responding.
It would be wise to set a read timeout, with conn.setReadTimeout(5000) (say). Adjust the timeout as necessary.
Check response code
int response = connection.getResponseCode();
If you get 301 it means that your resource is redirected. Try to change URI from http to https.
It helped in my case.
I'm trying to get my user information from stackoverflow api using a simple HTTP request with GET method in Java.
This code I had used before to get another HTTP data using GET method without problems:
URL obj;
StringBuffer response = new StringBuffer();
String url = "http://api.stackexchange.com/2.2/users?inname=HCarrasko&site=stackoverflow";
try {
obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
But in this case I'm getting just stranger symbols when I print the response var, like this:
�mRM��0�+�N!���FZq�\�pD�z�:V���JX���M��̛yO^���뾽�g�5J&� �9�YW�%c`do���Y'��nKC38<A�&It�3��6a�,�,]���`/{�D����>6�Ɠ��{��7tF ��E��/����K���#_&�yI�a�v��uw}/�g�5����TkBTķ���U݊c���Q�y$���$�=ۈ��ñ���8f�<*�Amw�W�ـŻ��X$�>'*QN�?�<v�ݠ FH*��Ҏ5����ؔA�z��R��vK���"���#�1��ƭ5��0��R���z�ϗ/�������^?r��&�f��-�OO7���������Gy�B���Rxu�#:0�xͺ}�\�����
thanks in advance.
The content is likely GZIP encoded/compressed. The following is a general snippet that I use in all of my Java-based client applications that utilize HTTP, which is intended to deal with this exact problem:
// Read in the response
// Set up an initial input stream:
InputStream inputStream = fetchAddr.getInputStream(); // fetchAddr is the HttpURLConnection
// Check if inputStream is GZipped
if("gzip".equalsIgnoreCase(fetchAddr.getContentEncoding())){
// Format is GZIP
// Replace inputSteam with a GZIP wrapped stream
inputStream = new GZIPInputStream(inputStream);
}else if("deflate".equalsIgnoreCase(fetchAddr.getContentEncoding())){
inputStream = new InflaterInputStream(inputStream, new Inflater(true));
} // Else, we assume it to just be plain text
BufferedReader sr = new BufferedReader(new InputStreamReader(inputStream));
String inputLine;
StringBuilder response = new StringBuilder();
// ... and from here forward just read the response...
This relies on the following imports: java.util.zip.GZIPInputStream; java.util.zip.Inflater; and java.util.zip.InflaterInputStream.
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.
I am sending json string in an https post request to an apache servert(request sends json data to a cgi-bin script that actually is a python script). Am using a standard cgi call -
f=open("./testfile", "w+")
f.write("usageData json = \n")
<b>form = cgi.FieldStorage()
formList = ['Data']
str = form['Data'].value
str = json.dumps(backupstr)
</b>
print backupstr
to read the json string in the url. Problem is that the script is not reading the json in the url even though the script is getting fired (the basic print statements are executing ...). This is how am sending data from the post side :
HttpsURLConnection connection = null;
try{
connection = (HttpsURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/json");
connection.setRequestProperty("Content-Length", "" +
Integer.toString(jsonstring.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
//wr.writeBytes(jsonstring);
wr.writeUTF(URLEncoder.encode(jsonstring, "UTF-8"));
wr.flush ();
wr.close ();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
}
rd.close();
//response = httpClient.execute(request);
}
catch (Exception e)
{
System.out.println("Exception " + e.getMessage());
throw e;
}
I suspect am missing one or more of the connection.setRequestProperty() settings on the sending end that's why it's firing the script but not reading the json string in the url ...what am I doing wrong ...?
currently i am using the following code to interact with server
public String connectToserverforincomingmsgs(String phonurl, String phno)
throws IOException {
URL url = new URL(phonurl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoInput(true);
// Allow Outputs
con.setDoOutput(true);
con.connect();
BufferedWriter writer = null;
writer = new BufferedWriter(new OutputStreamWriter(
con.getOutputStream(), "UTF-8"));
// give server your all parameters and values (replace param1 with you
// param1 name and value with your one's)
writer.write("sender_no=" + phno);
writer.flush();
String responseString = "";
BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
responseString = responseString.concat(line);
}
con.disconnect();
return responseString;
}
how could i make tcp connection .right now i don't have any idea . i am new to android and java aswell so any sample code about the tcp connection would be appreciated
To create a TCP Connection you need to Use Socket:
Socket socket = new Socket(host_name_or_ip_address, port_no);
To Send Data use socket.getOutputStream()
To Receive Data use socket.getInputStream()
Just replace HttpURLConnection with Socket. It works pretty much the same