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";
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
#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();
}
The parameter param1=world.But when i run the web service,I am getting json string as {"Hello":null} instead of {"Hello":"world"}.Please suggest for any changes.I think the problem is with annotation i.e #QueryParam.If this is the case,then please provide proper way to access the parameter using proper annotation.
Related
I am calling Traccar API from my AsyncTask class. I need to pass JSON and Basic Authentication using POST method. I have this inside my doInBackground but it returns 400 Bad Request. I cannot pinpoint what's wrong. I'm pretty sure URL and credentials are all correct.
String credentials= "my_username:my_password";
String credBase64 = Base64.encodeToString(credentials.getBytes(), Base64.DEFAULT).replace("\n", "");
URL url = new URL("https://server.traccar.org/api/devices");
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Authorization", credBase64);
if (this.postData!=null)
{
OutputStreamWriter writer = new OutputStreamWriter(urlConnection.getOutputStream());
writer.write(this.postData.toString());
writer.flush();
}
int statusCode = urlConnection.getResponseCode();
if(statusCode == 200)
{
InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
String response = inputStream.toString();
}
else
{
Log.e(TAG, "Error" + statusCode);
}
I write this controller and the main idia is that i want to login in another my web application using Post REQUEST. I tested it and the response is 200 OK ! but the controller only redirects me without log me in the another application. Please help.
#Controller
public class BackdoorLoginController {
private final String USER_AGENT = "Mozilla/5.0";
#RequestMapping(value = "/loginTo", method = RequestMethod.GET)
public void redirectWithUsingRedirectPrefix(HttpServletResponse res, HttpServletRequest request)
throws IOException, ServletException {
#SuppressWarnings("restriction")
URL url = new URL(null, "http://www.url.com", new sun.net.www.protocol.https.Handler());
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
String urlParameters = "submit=1&email=email#email.com&pass=password";
byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
int postDataLength = postData.length;
// add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("charset", "utf-8");
con.setRequestProperty("Host", "http://www.url.com");
con.setUseCaches(false);
con.setDoOutput(true);
con.setRequestProperty("Content-Length", Integer.toString(postDataLength));
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
try (DataOutputStream q = new DataOutputStream(con.getOutputStream())) {
q.write(postData);
}
// 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());
res.sendRedirect("http://www.url.com");
}
}
I am trying to write a simple HTTP server in Java that can handle POST requests. While my server successfully receives the GET, it crashes on the POST.
Here is the server
public class RequestHandler {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/requests", new MyHandler());
server.setExecutor(null); // creates a default executor
server.start();
}
static class MyHandler implements HttpHandler {
public void handle(HttpExchange t) throws IOException {
String response = "hello world";
t.sendResponseHeaders(200, response.length());
System.out.println(response);
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
}
And here is the Java code I use to send the POST
// HTTP POST request
private void sendPost() throws Exception {
String url = "http://localhost:8080/requests";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";
// 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());
}
Each time the POST request crashes on this line
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
but when I change the URL to the one provided in the example where I found this it works.
Instead of
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
Use
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
You are connecting to a URL which is not HTTPS. When you call obj.openConnection(), it decides whether the connection is HTTP or HTTPS, and returns the appropriate object. When it's http, it won't return an HttpsURLConnection, so you cannot convert to it.
However, since HttpsURLconnection extends HttpURLConnection, using HttpURLConnection will work for both http and https URLs. The methods that you are calling in your code all exist int the HttpURLConnection class.
The input I have are a URL and a request payload.
Say,
URL: https://somesresource.com
Payload: {userId: "4566"}
The output I get back is a Json with several key-value pairs.
I tried doing this in Rest Console and the output(Json) looked good. But, when I try to run the following program the output is not the json but the file(html i suppose) from the URL's server. How do I retrieve the Json instead of the file?
#Transactional
#RequestMapping(value = "/xxx", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody
String consumer() throws Exception {
String line;
String userId = "12345";
StringBuffer jsonString = new StringBuffer();
URL url = new URL("https://somewebsite/userprofile");
String payload="{\"userId\":\""+sid+"\"}";
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
try {
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
writer.write(payload);
writer.close();
System.out.print(connection.getInputStream().toString());
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
br.close();
connection.disconnect();
}
catch(Exception e) {
}
return jsonString.toString();
}
I think you are missing a converter in your application. I use RestFul Web service with Spring and use MappingJacksonHttpMessageConverter for to & fro conversion of JSON. Please provide more details of your configuration if you are looking for a specific answer.
I have a server and a client,
on the server side i have this handler
#Override
public void handleHttpRequest(HttpRequest httpRequest,
HttpResponse httpResponse,
HttpControl httpControl) throws Exception {
// ..
}
The question is how to send data from the client side and what method in the server side will contain the data sent?
If there is a better way to perform the communication using webbit, it will be welcomed too.
In a POST request, the parameters are sent as a body of the request, after the headers.
To do a POST with HttpURLConnection, you need to write the parameters to the connection after you have opened the connection.
This code should get you started:
String urlParameters = "param1=a¶m2=b¶m3=c";
String request = "http://example.com/index.php";
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
connection.setUseCaches (false);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
connection.disconnect();
Alternatively you could use this helper to send POST the request and get the request
public static String getStringContent(String uri, String postData,
HashMap<String, String> headers) throws Exception {
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost();
request.setURI(new URI(uri));
request.setEntity(new StringEntity(postData));
for(Entry<String, String> s : headers.entrySet())
{
request.setHeader(s.getKey(), s.getValue());
}
HttpResponse response = client.execute(request);
InputStream ips = response.getEntity().getContent();
BufferedReader buf = new BufferedReader(new InputStreamReader(ips,"UTF-8"));
if(response.getStatusLine().getStatusCode()!=HttpStatus.SC_OK)
{
throw new Exception(response.getStatusLine().getReasonPhrase());
}
StringBuilder sb = new StringBuilder();
String s;
while(true )
{
s = buf.readLine();
if(s==null || s.length()==0)
break;
sb.append(s);
}
buf.close();
ips.close();
return sb.toString();
}
Usually one will extend HttpServlet and override doGet.
http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServlet.html
I am not familiar with webbit but I do not think it is a Servlet webserver. It mentions that it serves static pages.