I have the code of the servlet where I want to get a valid response. This is the original layout of the request
{
"function": "Check",
"teamId": "<teamId>",
"teamKey": "<teamKey>",
"requestId": "<request-id>",
"firstName": "<FirstName>",
"lastName": "<LastName>",
"ticketNumber": "<ticket-num>"
}
I have this within my servlet in Intellij.
import com.google.gson.*;
import com.google.*;
import org.apache.*;
import org.apache.http.*;
#WebServlet(name = "Logincheck", urlPatterns = {"/Logincheck"})
public class Servlet extends HttpServlet {
String teamID = "IC106-2";
String teamKey = "1b3741ccf6d9ec5245055370125d901e";
String url="http://fys.securidoc.nl:11111/Ticket";
int Min = 1;
int Max = 100;
int REQ_ID = Min + (int)(Math.random() *((Max - Min)+1));
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//index.html form user input
String fname = request.getParameter("firstName");
String lastName = request.getParameter("lname");
String ticketNummer = request.getParameter("ticketnr");
JsonParser parser = new JsonParser();
URL object=new URL(url);
String ticketCheck = "{\"function:\"Check\",\"teamId\":\"IC106-2\",\"teamKey\":\"1b3741ccf6d9ec5245055370125d901e\",\"requestId\":\""+REQ_ID+"\",\"firstName\":\""+fname+"\",\"lastName\":\""+lastName+"\",\"ticketNumber\":\""+ticketNummer+"\"}";
HttpURLConnection con = (HttpURLConnection) object.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");
con.setRequestMethod("POST");
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
writer.write(ticketCheck);
writer.flush();
StringBuilder sb = new StringBuilder();
String jsonResponseString = sb.toString();
JsonElement jsonTree = parser.parse(jsonResponseString);
int HttpResult = con.getResponseCode();
if (HttpResult == HttpURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
System.out.println("" + sb.toString());
} else {
System.out.println(con.getResponseMessage());
}
}
Now when I hit run it opens my index.html and when I click the login button to /Logincheck it responses(within intellij):
Bad Request
The Teamkey and TeamID are 100% correct, but I'm probably overlooking something that has to do with Json. I have minimal experience with Json and servlets in general. Like do I make hardcoded login and ticket credentials, or is the input of the user correct already correct? I should expect this response:
{
"ticketStatus": "<ticket-status>",
"requestId": "<request-id>",
"result": "<result-code>",
"resultText": "<result-text>"
}
You should write your json data to request body. For this you can use OutputStreamWriter class to write to the output stream of HttpURLConnection like below:
String ticketCheck = "{ \"function\":\"Check\",\"teamId\":IC106-2,\"teamKey\":1b3741ccf6d9ec5245055370125d901e,\"requestId\":1,\"firstName\":\"" + fname + "\" ,\"lastName\":\""+lastName+"\",\"ticketNumber\":\"\"" + ticketnummer + "\"}";
HttpURLConnection con = (HttpURLConnection) object.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");
con.setRequestMethod("POST");
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
writer.write(ticketCheck);
//this line closes the outputstream and actually makes the http request is sent
writer.flush();
Solved. Simple quote typo. "bad request" means bad syntax and I forgot to add \" next to function.
String ticketCheck = "{\"function\":\"Check\",\"teamId\":\"IC106-2\",\"teamKey\":\"1b3741ccf6d9ec5245055370125d901e\",\"requestId\":\""+REQ_ID+"\",\"firstName\":\""+fname+"\",\"lastName\":\""+lastName+"\",\"ticketNumber\":\""+ticketNummer+"\"}";
correct json above
Related
I have spring boot application in which I get the streamName as a parameter, but now I don't want it to work in postman, but in another program in which the streamName is String that is created when calling a function. Previously I was giving it as json, but now I want to give it as parameter and I have no idea how can I do it.
This is my Request in Spring boot:
#PostMapping
#ResponseBody
public String addStream(#RequestParam("streamName") String streamName) {
String key = getRandomHexString();
streamService.addStream(new Stream(streamName,key));
return key;
}
and this is in another program where i want to make this method:
public void onHTTPPostRequest(String streamName) throws IOException {
PostResponse postResponse = new PostResponse();
postResponse.setStreamName(streamName);
Gson gson = new Gson();
String jsonString = gson.toJson(postResponse);
getLogger().info("POST Body " + jsonString);
URL pipedreamURL = new URL("http://10.100.2.44:8080/api?streamName=");
HttpURLConnection conn = (HttpURLConnection) pipedreamURL.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; utf-8");
conn.setRequestProperty("Accept", "application/json");
OutputStream os = conn.getOutputStream();
os.write(jsonString.getBytes("UTF-8"));
os.close();
int responseCode = conn.getResponseCode();
getLogger().info(responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
simply add it to the URL string:
URL pipedreamURL = new URL("http://10.100.2.44:8080/api?streamName=" + streamName);
Hello guys I am trying to send get request in java with header. I am looking for a method like conn.addHeader("key","value); but I cannot find it. I tried "setRequestProperty" method but it doest not work..
public void sendGetRequest(String token) throws MalformedURLException, IOException {
// Make a URL to the web page
URL url = new URL("http://api.somewebsite.com/api/channels/playback/HLS");
// Get the input stream through URL Connection
URLConnection con = url.openConnection();
//add request header
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Cache-Control", "no-cache");
con.setRequestProperty("Authorization", "bearer " + token);
InputStream is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
// read each line and write to System.out
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
It returns Httpresponse 401 error.
My office mate use unity c# to send get request header his codes looks like the fallowing.
JsonData jsonvale = JsonMapper.ToObject(reqDataGet);
// Debug.Log(jsonvale["access_token"].ToString());
// /*
string url = "http://api.somewebsite.com/api/channels/playback/HLS";
var request = new HTTPRequest(new Uri(url), HTTPMethods.Get, (req, resp) =>
{
switch (req.State)
{
case HTTPRequestStates.Finished:
if (resp.IsSuccess)
{
}
break;
}
});
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("Authorization", "bearer " + jsonvale["access_token"].ToString());
request.Send();
Any help?
In Java I think you want something like this.
String url = "http://www.google.com/search?q=stackoverflow";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", "My Example" );
int responseCode = con.getResponseCode();
I am trying to do a java rest web service using "POST" method.My client part to invoke the web service is working proper.But i am facing difficulty in accessing the passed parameters by "POST" method.Any help would be appreciable.
Here is my client side
public static void main(String[] args) throws IOException
{
String urlParameters = "param1=world¶m2=abc¶m3=xyz";
String request = "http://localhost:8080/wsRevDash/rest/post/test";
URL url = new URL(request);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("charset", "utf-8");
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
for (int c; (c = in.read()) >= 0;)
System.out.print((char)c);
}
And here is my java rest web service method to access the parameters(unable to access).
#POST
#Path("/test")
#Produces(MediaType.APPLICATION_JSON)
public String getpostdata(#QueryParam("param1") String param1,#QueryParam("param2") String param2)
{
JSONObject jObjDevice = new JSONObject();
jObjDevice.put("Hello",param1);
return jObjDevice.toJSONString();
}
When i run,I am getting
{"Hello":null} as json string instead of {"Hello":"world"}.Getting null means it is unale to access the passed parameters.Please do help.
You can use #QueryParam like shown below.
public String getpost( #QueryParam("param1") String param1,
#QueryParam("param2") String param2){
// Access both param below
}
To send data using POST request is quite straightforward.
Instead of conn.getOutputStream().write(postDataBytes); you'll have to use DataOutputStream to send data
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public static void main(String[] args) throws IOException
{
Map<String, String> params = new LinkedHashMap<String, String>();
params.put("param1", "hello");
params.put("param2", "world");
JSONObject myJSON = new JSONObject(params);
System.out.println(myJSON);
byte[] postData = myJSON.toString().getBytes(StandardCharsets.UTF_8);
int postDataLength = postData.length;
String request = "http://localhost:8080/wsRevDash/rest/post/test";
URL url = new URL(request);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("charset", "utf-8");
conn.setRequestProperty("Content-Length", Integer.toString(postDataLength));
//Try with Resources Example, just giving you an option
// try (DataOutputStream wr = new
// DataOutputStream(conn.getOutputStream()))
// {
// wr.write(postData);
// }
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.write(postData);
}
Note: You're sending application/json header in your request but I don't see a JSON in your code. It is advisable to send useful headers only
You can convert HashMap directly to JSONObject like,
org.json.JSONObject jsonObject = new org.json.JSONObject(params);
But this only works for Map<String, String>
To access the parameter in webservice, you'll have to accept JSONObject instead of accepting Map<String, String>.
public String getpost(JSONObject params) throws JSONException
{
if(params.has("param1"))
System.out.println(params.getString("param1"));
if(params.has("param2"))
System.out.println(params.getString("param2"));
//IMPLEMENT YOUR LOGIC HERE AND THEN RETURN STRING
return "your_return string";
}
Using http in java (eclipse) I have to POST a message using a given url with header of http authorization as 64 base encoded message and body has the information like grant type,password,username ,scope.There is a given content type,password,username.I want the client code and using it I should be able to get the message from the server and show that message as the output.
Here is a sample code
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
String userpass = username + ":" + password;
String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());
con.setRequestProperty ("Authorization", basicAuth);
con.setRequestMethod("POST");
con.setConnectTimeout(timeout);
con.setDoOutput(true);
con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream ());
wr.write(requestString);
wr.flush ();
wr.close ();
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.t
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class HttpClassExample {
public static void main(String[] args) throws Exception {
HttpClassExample http = new HttpClassExample();
System.out.println("Testing Send Http POST request");
http.sendPost();
}
// HTTP POST request
private void sendPost() throws Exception {
String userName="world#gmail.com";
String password="world#123";
String url = "https://world.com:444/idsrv/issue/oauth2/token";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
String ClientId = "mmclient";
String ClientSecret = "norZGs5vkw+cmlKROazauMrZInW9jokxIRCmndMwc+o=";
String userpass = ClientId + ":" + ClientSecret;
String basicAuth = "Basic "+" "
+ javax.xml.bind.DatatypeConverter.printBase64Binary(userpass
.getBytes());
con.setRequestProperty("Authorization", basicAuth);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type","Application/x-www-form-urlencoded");
String urlParameters = "grant_type=password&username="+userName+"&password="+password+"&scope=urn:meetingmanagerservice";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}
}
I'm trying to call an URL (URL contains only json code) from a servlet but I keep getting a read time out exceptions on getInputStream().
public class SimpleServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse esponse) throws IOException, ServletException {
BufferedReader reader = null;
StringBuilder stringBuilder;
InputStream in=null;
String json=null;
URL url = new URL("http://localhost:8080/SimpleWeb/users");
try{
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-type", "application/json");
conn.setReadTimeout(5000);
conn.connect();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
stringBuilder = new StringBuilder();
String line=null;
while((line = reader.readLine()) != null){
stringBuilder.append(line + "\n");
}
json = stringBuilder.toString();
System.out.println(json);
}catch(Exception e){
System.out.println(e);
}finally{
if(reader!=null)
reader.close();
}
}
}
The code works by replacing http://localhost:8080/SimpleWeb/users with http://localhost:8080/SimpleWeb/users.txt(but only when called from a plain java app, not a servlet)
Can anyone help to see what I might be doing wrong?