I'm trying to create a client server application and I'm currently stuck. I have this java code on my client.
HttpURLConnection connection;
connection = (HttpURLConnection) new URL("http://www.masterpaint.gr/login.php").openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content-Type","application/json; charset=UTF-8");
connection.setRequestProperty("Accept","application/json: charset=UTF-8");
connection.setRequestMethod("POST");
System.out.println("The request method on client end is " + connection.getRequestMethod());
System.out.println("Server response to connection " + connection.getResponseMessage());
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String buffer;
StringBuilder stringBuilder = new StringBuilder();
while ((buffer = reader.readLine()) != null) {
stringBuilder.append(buffer);
}
System.out.println("The request methond on server end is " + stringBuilder.toString());
And this is the simple test php code on the server.
<?php echo $_SERVER['REQUEST_METHOD']; ?>
Whenever I run this test java program and try to connect I get the same output.
The request method on client end is POST
Server response to connection OK
The request methond on server end is GET
The php script always echoes back that I'm sending a GET request even though
my java code states that use a POST. I have tried connecting to the script through postman using different request methods and it's all fine, so the problem must be in the Java code. Any insight would be greatly appreciated.
I am not having any experience of php but it seems like it is looking for content-length header which will not be send in your case so it is treating this as GET request.
HttpURLConnection connection;
connection = (HttpURLConnection) new URL("http://www.masterpaint.gr/login.php").openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content-Type","application/json; charset=UTF-8");
connection.setRequestProperty("Accept","application/json: charset=UTF-8");
connection.setRequestMethod("POST");
connection.setFixedLengthStreamingMode(0);
System.out.println("The request method on client end is " + connection.getRequestMethod());
System.out.println("Server response to connection " + connection.getResponseMessage());
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String buffer;
StringBuilder stringBuilder = new StringBuilder();
while ((buffer = reader.readLine()) != null) {
stringBuilder.append(buffer);
}
System.out.println("The request methond on server end is " + stringBuilder.toString());
This will set content length 0 as you are not sending any content.
Related
I just want to start Nifi processor through REST API java code, i am able to invoke HTTP connection and able to see play button on processors but flow is not happening? and i have multiple processes group in which my first processor is GETSplunk Template which is in cron driven ,manual start is good and fine and when i start through API flow is not working, and changed to Timer schedule it is showing error for SQL template ,can any one bumped with this issue, please suggest me.
sample API code is.
String url = "http://hostname:8080/nifi-api/flow/process-groups/{id};
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// Setting basic put request
con.setDoOutput(true);
con.setRequestMethod("PUT");
con.setRequestProperty("Content-Type","application/json");
String putJsonData = "{\r\n" +
"\"component\":{\r\n" +
"\"id\":\"<processor-group id>\",\r\n " +"\"state\":\"RUNNING\"\r\n" + "}";
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
wr.write(putJsonData);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("nSending 'POST' request to URL : " + url);
System.out.println("Post Data : " + putJsonData);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader( new
InputStreamReader(con.getInputStream())); String output; StringBuffer
response = new StringBuffer();
while ((output = in.readLine()) != null) { response.append(output); }
in.close();
//printing result from response
System.out.println(response.toString());
}
#Sravya99 When I need to trigger flow from outside of Nifi, I often create a NiFi API interface listening on a port via HandleHttpRequest and HandleHttpResponse. This can be very simple request, or very complicated with ssl, access and authorization, etc. It should serve fine for your purpose, leaving your flow always on, and initiating the triggered responses using the HandleHttpRequest.
I am trying to call a web service using a java code which is throwing java.io.EOFException: Response had end of stream after 0 bytes for the large chunk of data.
The same web service call works in Postman REST Client, but Java code throws an error and it is not able to fetch web service response.
Can someone please help me with this?
Below is the code snippet for reference:
String output;
URL url = new URL(wsUrl); //wsUrl is a web service URL
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
String authorization = "**************" + ":" + "*********";
String basicAuth = "Basic " + java.util
.Base64
.getEncoder()
.encodeToString(authorization.getBytes());
conn.setRequestProperty("Authorization", basicAuth);
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
System.out.println("Output from Server .... \n");
String jsonstring = new String();
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
My goal is to create a realtime service alert feed and send it over to a server that I made in Java with an HTTP post request. The first step I did was to create a copy of the example alert feed posted here and it seems I was successfully able to do that as I was able to print it out the message. https://developers.google.com/transit/gtfs-realtime/examples/alerts
The next step that I did is to create an HTTP connection and send the feed over with the POST request. This is what I have in my client code and example here is the feed name.
String url = "https://localhost:8080";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest 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/x-protobuf");
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
example.build().writeDelimitedTo(wr);
wr.flush();
wr.close();
My server code is simply this so far.
ServerSocket server = new ServerSocket(8080);
System.out.println("Listening for connection on port 8080 ....");
while (true) {
try (Socket socket = server.accept()) {
FeedMessage feed = FeedMessage.parseDelimitedFrom(socket.getInputStream());
Date today = new Date();
String httpResponse = "HTTP/1.1 200 OK\r\n\r\n" + today;
socket.getOutputStream().write(httpResponse.getBytes("UTF-8"));
}
}
The question here is that I get the Protocol message contained an invalid tag 0 on the server side. I would like some help on trying to resolve this issue. Maybe I am not parsing it correctly.
Update #2
I have tried to parse the HTTP headers to get to the payload like comments have said. But my code hangs and the output to print the headers on the terminal looks serialized.
DataInputStream isr = new DataInputStream(socket.getInputStream());
Reader reader = new InputStreamReader(isr);
BufferedReader reader2 = new BufferedReader(reader);
String line = reader2.readLine();
System.out.println("get lines");
while (!line.isEmpty()) {
System.out.println(line);
line = reader2.readLine();
}
You are dealing with raw sockets at the server, but the payload is encoded in an http request body. You are going to need to parse the http request through to the payload, and when you have just the body : send that to protobuf. Right now, you're sending the http headers to protobuf, which doesn't make sense. That could mean parsing through to \r\n\r\n, but it would help if you could make use of the content-length header, and even better if you can use a pre-built http library.
I am new to user java to connect to server. I have succeed in forming a json which has some key and value to form the body to call the api service and get successful response (with the following code).
My questions are:
Some of my web service just request header info, for example, I just need to
put the ApiKey(key name) and key value in the header and send to server, no other info is needed in body, how can I do this?
Some of my web service require both header info and body info, how can I construct the json and send to server?
try {
String input = jsonString;
URL url = new URL("https://example.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
System.out.println("errorcode" + conn.getResponseCode());
if (conn.getResponseCode() != 200) {
JOptionPane.showMessageDialog(new JFrame(), "Please input a correct username or password");
return;
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String jsonText = read(br);
System.out.println("jsonText: " + jsonText);
I'm trying to send a PUT request from a Java app to a server. I successfully send GET, POST and DELETE requests but the PUT one won't succeed (I'm getting a 401 Error with the code below, 405 Error with an other code using the HttpPut of the apache package).
I'm using java.net.HttpURLConnection, here is a small region of my code :
URL obj = new URL(urlPost);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add request header
con.setRequestMethod(typeRequest); //typeRequest = PUT
String credentials = adminOC + ":" + pwdOC;
String encoding = Base64.encode(credentials.getBytes("UTF-8"));
con.setRequestProperty("Authorization", String.format("Basic %s", encoding));
if (!typeRequest.equals("GET")){
con.setDoOutput(true);
try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
wr.writeBytes(postParam);
wr.flush();
}
}
if (con.getResponseCode() == 200){
try (BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()))) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
response += inputLine;
}
}
}
I tried sending my PUT parameters the "POST" way and also directly in the URL.
It seems to be an error from my Java code and not from the server because I tried to do the PUT request with cURL and it worked.
Thanks for reading, I hope you will be able to give me some hints to debug the problem.
What is missing in your code is con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded")