On client side , following android code would make the call to the local server :
String link = "http://localhost:8080/test/cgi-bin/test.py";
URL url = null;
try {
url = new URL(link);
HttpURLConnection client = (HttpURLConnection) url.openConnection();
JSONObject jo = new JSONObject();
jo.put("desc","xyz");
String data2 = jo.toString();
client.setRequestMethod("Post");
// client.setRequestProperty("key","value");
client.setDoOutput(true);
OutputStreamWriter outputPost = new OutputStreamWriter(client.getOutputStream());
outputPost.write(data2);
outputPost.flush();
outputPost.close();
Earlier I was using servlets to interact with DB as the code below :
Using HttpServlet class , i could get the request and its parameters :
public class ServletXYZ extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String method = request.getParameter("method");
Is there any way in python which allows me to do the same (getting parameter values from request) ?
Thanks.
I've used CherryPy as a general purpose HTTP server framework. Ultimately to do the same as the servlet, there are many links - this one seems to be pretty much what you want.
Related
In a Java HttpServlet, is it possible to request data from another local service using the original request's header information without necessarily forwarding?
For example, I have FooBar.java:
// Handles the url at /foo/bar and can be accessed at http://localhost/foo/bar
public class FooBar extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
Object data = ... // 1. Retrieve data at http://localhost/foo/baz utilizing the current request's header
Object newData = doSomething(data); // 2. Process the data
response.getWriter().write(newData.toString); // 3. Return the processed data
}
private Object doSomething(Object data)
{
// Perform some business logic
}
}
Step 1 is the issue here. The purpose of this is that I want to be able to perform some sort of logic on the data before returning it in full, but don't necessarily have access do make the changes on the handler at /foo/baz do to the propriety nature of things.
You can use this answer of me to create a HTTP Request: send get request
In addition, it may be necessary to copy the request header with some care:
private static final Set forbiddenCopyHeaders = new HashSet<>(Arrays.asList(new String[]{
"connection"
, "transfer-encoding"
, "content-length" // POST kann zu Status 500 führen, wenn die content-length kopiert wird
, "via"
, "x-forwarded-for"
, "x-forwarded-host"
, "x-forwarded-server"
}));
private void copyRequestHeaders(HttpServletRequest customerRequest, HttpRequestBase internRequest) throws
HttpException
{
Enumeration<String> headerNames = customerRequest.getHeaderNames();
String connectionHeader = customerRequest.getHeader("connection");
while (headerNames.hasMoreElements())
{
String headerName = headerNames.nextElement();
boolean copyAllowed = !forbiddenCopyHeaders.contains(headerName.toLowerCase()) &&
!StringUtils.containsIgnoreCase(connectionHeader, headerName);
if (copyAllowed)
{
Enumeration<String> values = customerRequest.getHeaders(headerName);
while (values.hasMoreElements())
{
internRequest.addHeader(headerName, values.nextElement());
}
}
}
setProxySpecificRequestHeaders(customerRequest, internRequest);
}
private void setProxySpecificRequestHeaders(HttpServletRequest customerRequest,
HttpRequestBase internRequest) throws HttpException
{
String serverHostName = "doorman";
try
{
serverHostName = InetAddress.getLocalHost().getHostName();
}
catch (UnknownHostException e)
{
logger.error("Couldn't get the hostname needed for headers x-forwarded-server and Via", e);
}
String originalVia = customerRequest.getHeader("via");
StringBuilder via = new StringBuilder("");
if (originalVia != null)
{
if (originalVia.contains(serverHostName))
{
logger.error("This proxy has already handled the Request, will abort.");
throw new HttpException("Request has a cyclic dependency on this proxy.");
}
else
{
via.append(originalVia).append(", ");
}
}
via.append(customerRequest.getProtocol()).append(" ").append(serverHostName);
internRequest.addHeader("via", via.toString());
internRequest.addHeader("x-forwarded-for", customerRequest.getRemoteAddr());
internRequest.addHeader("x-forwarded-host", customerRequest.getServerName());
internRequest.addHeader("x-forwarded-server", serverHostName);
internRequest.addHeader("accept-encoding", "");
}
Using HttpURLConnection and altering the header to include a property from the original request, I was able to get a BufferedReader from the HTTP request:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
// Step 1
String serverName = request.getLocalName();
String contextPath = request.getContextPath();
URL url = new URL("https://" + serverName + contextPath + "/baz");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Key Header", request.getHeader("Key Header"));
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
// Step 2
... // Do something with the data from the reader
// Step 3
... // Write the data back using the response
}
I need to send additional data to the server side while uploading files with dojo. How do I do that?
I'm using the upload method of the dojo file uploader. I want to dynamically pass an additional variable for file destination on the server side.
My JavaScript code:
function(Uploader, FileList, dom, on, Carousel, ContentPane, SwapView) {
dojo.ready(function() {
var form = dojo.byId("myForm");
var uploaderDIV = dojo.byId("uploader");
up = new Uploader({
label: 'Attach Files',
multiple: true,
showInput: 'before',
name : 'uploadedfiles[]',
url: '/TestServer/rest-services/submitForm',
}).placeAt(uploaderDIV);
And my server side code:
#Path("/submitForm")
#POST
#Consumes("multipart/form-data")
#Produces({MediaType.TEXT_HTML, MediaType.APPLICATION_JSON})
public Response uploadFile(MultipartFormDataInput input) {
String fileName = "";
Map<String, List<InputPart>> formParts = input.getFormDataMap();
I would recommend using Apache FileUpload here, as it will greatly simplify your life. In my implementations I have set up a servlet mapped to the upload URL and handled the request in a doPost method:
public class MyServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// ...
}
}
Piggybacking on the information provided by bishop directly in response to your question, you can attach URL parameters using the ? and & characters (i.e. ?one=one&two=two). On the server side you'll need to read those URL parameters from the request:
String one = request.getParameter("one");
String two = request.getParameter("two");
I want to create an application that will fetch a JSON object from a servlet to deserialize it, and then use its variables to do other things.
My servlet has the following code in the doPost:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ObjectOutputStream os;
os = new ObjectOutputStream(response.getOutputStream());
String s = new String("A String");
Gson gson = new Gson();
String gsonObject= gson.toJson(s);
os.writeObject(gsonObject);
os.close();
}
Now, while the servlet is running, I can access it via a browser, if I post same code in the doGet method, that would download a servlet file, which is not what I want.
What should I use in my second application that would connect to the servlet, fetch the object, so that I can manipulate it later?
Thanks in advance.
You need few changes in your servlet :
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String s = new String("A String");
String json = new Gson().toJson(s);
this.response.setContentType("application/json");
this.response.setCharacterEncoding("UTF-8");
Writer writer = null;
try {
writer = this.response.getWriter();
writer.write(json);
} finally {
try {
writer.close();
}
catch (IOException ex) {
}
}
}
If its downloading the servlet file instead of showing it in the browser , most probably you have not set the content type in the response. If you are writing a JSON string as the servlet response , you have to use
response.setContentType("text/html");
response.getWriter().write(json);
Please note the order , its "text/html" and not "html/text"
IfI understood the question correctly then you can use, java.net.HttpURLConnection and java.net.URL objects to create a connection to this servlet and read the JSON streamed by the above JSON servlet in your second servlet.
Hi i am trying to create a GAE/J app in which i have to retrieve access token from a given code
so here is my code for /oauth2callback servlet
public class OAuth2Callback extends HttpServlet{
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
String url = "https://accounts.google.com/o/oauth2/token";
// FetchOptions opt = FetchOptions.Builder.doNotValidateCertificate();
URL url1=new URL(url);
String param="grant_type=authorization_code&code="+req.getParameter("code")+"&client_id=anonymouns&client_secret=anonymous&redirect_uri=https://www.cloudspokestest.appspot.com/oauth2callback";
HttpURLConnection connection =
(HttpURLConnection)url1.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
connection.getOutputStream().write( param.getBytes() );
InputStream str= connection.getInputStream();
BufferedReader reader=new BufferedReader(new InputStreamReader(str));
String l="";
while((l=reader.readLine())!=null){
resp.getWriter().println(l);
}
}
}
but on the browser screen i am getting error invalid grant with response code 400.can any one please help how to remove this error.
You're getting this error most likely because the parameter values in your url are not url-encoded. The value of the redirect_uri, and possibly the value of code must be url-encoded.
You could use java.net.URLEncoder to encode the values.
Also never use getBytes() on a String, as it uses your platform's default character encoding to convert characters to bytes. Running the same code on another machine, or changing your machines configuration might give different output. Always use getBytes(charsetname) instead.
How can I configure tomcat so when a post request is made the request parameters are outputted to a jsp file? Do I need a servlet which forwards to a jsp or can this be handled within a jsp file ?
Here is my method which sends the post request to the tomcat server -
public void sendContentUsingPost() throws IOException {
HttpConnection httpConn = null;
String url = "http://LOCALHOST:8080/services/getdata";
// InputStream is = null;
OutputStream os = null;
try {
// Open an HTTP Connection object
httpConn = (HttpConnection)Connector.open(url);
// Setup HTTP Request to POST
httpConn.setRequestMethod(HttpConnection.POST);
httpConn.setRequestProperty("User-Agent",
"Profile/MIDP-1.0 Confirguration/CLDC-1.0");
httpConn.setRequestProperty("Accept_Language","en-US");
//Content-Type is must to pass parameters in POST Request
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// This function retrieves the information of this connection
getConnectionInformation(httpConn);
String params;
params = "?id=test&data=testdata";
System.out.println("Writing "+params);
// httpConn.setRequestProperty( "Content-Length", String.valueOf(params.length()));
os = httpConn.openOutputStream();
os.write(params.getBytes());
} finally {
if(os != null)
os.close();
if(httpConn != null)
httpConn.close();
}
}
Thanks
First of all, your query string is invalid.
params = "?id=test&data=testdata";
It should have been
params = "id=test&data=testdata";
The ? is only valid when you concatenate it to the request URL as a GET query string. You should not use it when you want to write it as POST request body.
Said that, if this service is not supposed to return HTML (e.g. plaintext, JSON, XML, CSV, etc), then use a servlet. Here's an example which emits plaintext.
String id = request.getParameter("id");
String data = request.getParameter("data");
response.setContentType("text/plain");
response.setContentEncoding("UTF-8");
response.getWriter().write(id + "," + data);
If this service is supposed to return HTML, then use JSP. Change the URL to point to the JSP's one.
String url = "http://LOCALHOST:8080/services/getdata.jsp";
And then add the following to the JSP template to print the request parameters.
${param.id}
${param.data}
Either way, you should be able to get the result (the response body) by reading the URLConnection#getInputStream().
See also:
How to use URLConnection to fire and handle HTTP requests?
Unrelated to the concrete problem, you are not taking character encoding carefully into account. I strongly recommend to do so. See also the above link for detailed examples.
A servlet can handle both get and post request in following manner:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//remaning usedefinecode
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
If you have a tomcat installation from scratch, don't forget to add the following lines to web.xml in order to let the server accept GET, POST, etc. request:
<servlet>
<servlet-name>default</servlet-name>
<servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
...
<init-param>
<param-name>readonly</param-name>
<param-value>false</param-value>
</init-param>
...
</servlet>