Using cookies from httpclient in webview - cookies

In my app I'm sending a device ID to a server using http post and I'm getting a session ID back. Now I need to get the session cookie in my webviewclient. I did some research and found this:
Android WebView Cookie Problem
The problem is the solution doesn't work for me. I keep getting an error on this line:
List<Cookie> cookies = httpClient.getCookieStore().getCookies();
The method getCookieStore() is undefined for HttpClient type. I should have all the right libraries loaded, so I don't know why I keep getting an error.
Here is my code, maybe someone will be able help me implement a solution to get the session cookie into my webview.
Thanks in advance!
package mds.DragonLords;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class Home extends Activity {
WebView mWebView;
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
private String tmDevice;
private String sid;
private String url;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final TelephonyManager tm = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
tmDevice = "2" + tm.getDeviceId();
postData();
url = "myserver"+sid.substring(5);
setContentView(R.layout.web);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new HelloWebViewClient());
mWebView.loadUrl(url);
}
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("myserver");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("uid", tmDevice));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
inputStreamToString(response.getEntity().getContent());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
private void inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sid = total.toString();
}
}

I've just ran into the same thing. I know it's an old post, but maybe it'll help somebody else.
The problem is in declaration of postData().
That line now is :
HttpClient httpclient = new DefaultHttpClient();
It should be:
DefaultHttpClient httpclient = new DefaultHttpClient();
see this: http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/client/DefaultHttpClient.html

Related

Extract SOAP custom header information

I want to read request header from SOAP incoming request in my Java code for some authorization purpose. I found few work-arounds like using SOAPHandlers and . Code as below :
`package com.cerillion.ccs.framework;
import java.util.HashSet;
import java.util.Set;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
import org.apache.log4j.Logger;
public class ApiSoapHandler implements SOAPHandler<SOAPMessageContext> {
private static final Logger logger = Logger.getLogger(ApiSoapHandler.class.getName());
#Override
public void close(MessageContext arg0) {
// TODO Auto-generated method stub
}
#Override
public boolean handleFault(SOAPMessageContext context) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean handleMessage(SOAPMessageContext context) {
logger.debug("Inside ApiSoapHandler");
try {
SOAPMessage message = context.getMessage();
SOAPHeader header = message.getSOAPHeader();
message.saveChanges();
} catch (SOAPException e) {
logger.error("Error occurred while adding credentials to SOAP header.",
e);
}
return true;
}
#Override
public Set<QName> getHeaders() {
/* QName securityTokenHeader = new QName("urn:com.intertech.secty", "token");
//new QName(“urn:com.intertech.secty”,“username”);
HashSet<QName> headers = new HashSet<QName>();
headers.add(securityTokenHeader);
return headers;*/
return null;
} }`
I ma really curious about to have some other simple alternative rather than writing entire handler just for fetching custom header tag. Is this the only way to read SOAP request header ? Any leads are really appreciated

DELETE giving 405 in postman

I am new to restful webservices and following java restful api tutorials.
all the HTTP requests are working fine except the DELETE request.
i am facing the same issue as described in this link.
REST - HTTP Status 405 - Method Not Allowed
also , in the predefined header values postman is showing
allow →GET,OPTIONS,PUT(image link is below)
i am following the correct syntax and url format as per the specification(pasted in image) but delete is not working.
allowed : GET,OPTIONS,PUT.img
please let me know where i am missing.
Edit : Source code :
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.koushik.javabrains.messenger.model.Message;
import org.koushik.javabrains.messenger.service.MessageService;
#Path("/messages")
public class MessageResource {
MessageService messageService = new MessageService();
#GET
#Produces(MediaType.APPLICATION_JSON)
public List<Message> getMessages(){
System.out.println("Hello There");
List<Message> returnedList = messageService.getAllMessages();
System.out.println(returnedList);
return returnedList;
}
#GET
#Path("/{messageId}")
#Produces(MediaType.APPLICATION_JSON)
public Message getMessage(#PathParam("messageId") long messageId){
System.out.println("Message returned");
return messageService.getMessage(messageId);
}
#POST
#Produces(MediaType.APPLICATION_JSON)
public Message addMessage(Message message){
return messageService.addMessage(message);
}
#PUT
#Path("/{messageId}")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Message updateMessage(#PathParam("messageId") long id , Message message){
message.setId(id);
return messageService.updateMessage(message);
}
#DELETE
#Path("/messageId")
#Produces(MediaType.APPLICATION_JSON)
public void deleteMessage(#PathParam("messageId") long id){
System.out.println("Hello There");
messageService.removeMessage(id);
}
}
package org.koushik.javabrains.messenger.service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.koushik.javabrains.messenger.database.DatabaseClass;
import org.koushik.javabrains.messenger.model.Message;
public class MessageService {
private Map<Long , Message> messages = DatabaseClass.getMessages();
public MessageService(){
messages.put(1L, new Message(1, "Hello World" , "koushik"));
messages.put(2L, new Message(2, "Hello Jersey" , "Koushik"));
}
public List<Message> getAllMessages(){
return new ArrayList<Message>(messages.values());
}
public Message getMessage(long id){
Message m = messages.get(id);
System.out.println("Value of message "+m);
return m;
}
public Message addMessage(Message message){
message.setId(messages.size()+1);
messages.put(message.getId(), message);
return message;
}
public Message updateMessage(Message message){
if(message.getId() <=0){
return null;
}
messages.put(message.getId(), message);
return message;
}
public Message removeMessage(long id){
return messages.remove(id);
}
}
package org.koushik.javabrains.messenger.database;
import java.util.HashMap;
import java.util.Map;
import org.koushik.javabrains.messenger.model.Message;
import org.koushik.javabrains.messenger.model.Profile;
public class DatabaseClass {
private static Map<Long , Message> messages = new HashMap();
private static Map<String , Profile> profiles = new HashMap();
public static Map<Long , Message> getMessages() {
return messages;
}
public static Map<String, Profile> getProfiles() {
return profiles;
}
}
except delete other requests are working fine.
on sending DELETE the server is returning HTTP -405 method not allowed.
also on sending delete request then in the header values postman is showing
allow →GET,OPTIONS,PUT
Thanks
Make sure you do not have any URL Parameters entered in Postman, also make sure you do not pass any headers in postman.
The delete request should be plain without and of these.
Also, the string message ID need to be put in curly brackets. That would be the reason for your 405 mostly.
Change path annotation as below and try.
#Path("/{messageId}")

Can't get my REST web service to work (using Glassfish in Netbeans)

I'm writing a fairly simple restful web service project in Netbeans (used the Maven Web Application template). I am trying to run it on a Glassfish 4.1 server. I have used Tomcat in the past, but that's not really an option here. Basically, my problem is that I run the project, the server starts, but I just get a 404 error when I try to access the service in the browser.
Here is my source code:
package jp.go.aist.limrs;
import com.hp.hpl.jena.rdf.model.Model;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.websocket.server.PathParam;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.apache.commons.io.IOUtils;
#Path("/target")
public class ParserService
{
public static final String SERVER_LOC = "http://localhost:8080/LiMRS/";
public static final String MAPPINGS_LOC = "export.txt";
private String targetUrl;
private String microData;
private Model uDataModel;
private Model mappingsModel;
public ParserService() {}
public ParserService( String url )
{
this.targetUrl = url;
try {
parseMicro(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
#GET
#Path("/{url:.+}")
#Produces(MediaType.TEXT_PLAIN)
public String getMicro(#PathParam("url") String target)
{
this.targetUrl = target;
String domain = "_";
try {
URI uri = new URI(this.targetUrl);
domain = uri.getHost();
System.out.println("Domain is " + domain + "\n\n\n");
} catch (URISyntaxException ex) {
Logger.getLogger(jp.go.aist.LiMRS.LiMRService.class.getName()).log(Level.SEVERE, null, ex);
}
this.microData = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<rdf:RDF xml:base=\"http://dbpedia.org/ontology/\" " +
"xmlns:_=\"" + domain + "\">\n\n";
try
{
parseMicro(URLEncoder.encode(this.targetUrl, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
return "";
}
return this.microData;
}
private void parseMicro(String target) throws MalformedURLException
{
try {
URL url = new URL("http://getschema.org/microdataextractor?url=" + target + "&out=rdf");
HttpURLConnection conn;
try {
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
InputStream ins = conn.getInputStream();
StringWriter writer = new StringWriter();
IOUtils.copy(ins, writer, null);
this.microData += writer.toString() + ".";
} catch (IOException ex) {
Logger.getLogger(jp.go.aist.LiMRS.LiMRService.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (MalformedURLException ex) {
Logger.getLogger(jp.go.aist.LiMRS.LiMRService.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
The URL I'm using to test the service is: http://localhost:8080/LiMRS/target/http://www.rottentomatoes.com/m/jurassic_park/
(I know the URL is unencoded. There are forward slashes in the 'resource' part of the URL, after "/target/", but that is taken care of by the regex in the code and is not source of the problem.)
It's possible the problem is with the server itself, I don't know if there is any special configuration that needs to be done to Glassfish or if you can just run the project outright. I don't have a web.xml file. Unless I'm mistaken, I don't think I need one. What am I missing here?
You're going to need a web.xml or a Application/ResourceConfig subclass to configure the application. If you don't want to use a web.xml, the easiest thing you can do is have an empty Application class annotated with #ApplicationPath. This will cause the registration of all #Path classes you have
#ApplicationPath("/")
public class JaxRsApplication extends Application {}
You can see more options here

How to send a XML request with httpclient and receive a file? (Java)

I need to send a XML request to a webservice which was not developed using SOAP protocoal. The webservice only works with pure XML request/answer, so there is not WSDL. The webservice will answer with a gzip file which I have to download. Can anyone help me please? I started with the code below. Thanks!
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
public class Teste {
public static void main(String[] args)
{
boolean success = XMLDataPost();
System.out.println(success);
}
private static boolean XMLDataPost(){
boolean success = false;
HttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httpPost = new HttpPost("http://webservice.blablabla.com.br");
StringEntity reqEntity = new StringEntity("<RequestVeiculo><login>02566288000191</login><senha>159828</senha></RequestVeiculo>");
reqEntity.setContentType("text/xml");
reqEntity.setChunked(true);
httpPost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
if(response.getStatusLine().getStatusCode() == 200){
success = true;
}
if (resEntity != null) {
System.out.println("Tamanho: " + resEntity.getContentLength());
System.out.println("Chunked?: " + resEntity.isChunked());
}
EntityUtils.consume(resEntity);
}
catch (Exception e) {
System.out.println(e);
}
finally {
httpclient.getConnectionManager().shutdown();
}
return success;
}
}

Jetty embed in Processing.org, static assets + POST

I'm trying to embed Jetty in a Processing Sketch. So far I made it working to serve static files (a html directory in the Sketch folder).
I want to react to one POST with a user input from one of the static pages.
As I have no knowledge on Jetty and coming from a PHP & Ruby (RoR) web programing background I am very confused with the way things go in Jetty.
I simply want something similar to routes where everything except e.g.
"localhost:8080/post?string=whatever"
is a static file.
The post?string=whatever should maybe trigger a function (in Processing) where the submitted String is handled.
I have been reading the Jetty docs a lot but couldn't figure out so far how to do it.
Thank you very much for any help!
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
String poststr;
void setup() {
Server server = new Server();
SelectChannelConnector connector = new SelectChannelConnector();
connector.setPort(8080);
server.addConnector(connector);
ResourceHandler resource_handler = new ResourceHandler();
resource_handler.setDirectoriesListed(true);
resource_handler.setWelcomeFiles(new String[] {
"index.html"
}
);
resource_handler.setResourceBase(sketchPath("")+"pftf");
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[] {
resource_handler, new DefaultHandler()
}
);
server.setHandler(handlers);
try {
server.start();
server.join();
}
catch(Exception e) {
};
}
Yes, Jetty can be very confusing in the beginning, especially when you only want to do a couple of simple things (not necessarily full-blown web applications).
The key to making this work is to use a ContextHandler for each of your other handlers (e.g. ResourceHandler). You can tell the ContextHandler which context (i.e. URL) it should respond to. After making a ContextHandler for the ResourceHandler and your custom Handler (e.g. PostHandler) you have to put both in a ContextHandlerCollection (uff...), so your Server knows what contexts exist.
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
void setup() {
/* Configure the http server */
Server server = new Server();
SelectChannelConnector connector = new SelectChannelConnector();
connector.setPort(8080);
server.addConnector(connector);
/* Resources */
ResourceHandler resourceHandler = new ResourceHandler();
resourceHandler.setDirectoriesListed(true);
resourceHandler.setWelcomeFiles(new String[] {
"index.html"
}
);
resourceHandler.setResourceBase(sketchPath("")+"pftf");
ContextHandler resourceContext = new ContextHandler();
resourceContext.setContextPath("/");
resourceContext.setHandler(resourceHandler);
/* Post API */
PostHandler postHandler = new PostHandler();
ContextHandler postContext = new ContextHandler();
postContext.setContextPath("/post");
postContext.setHandler(postHandler);
ContextHandlerCollection contexts = new ContextHandlerCollection();
contexts.setHandlers(new Handler[] {
resourceContext, postContext
}
);
server.setHandler(contexts);
/* Start the server (finally) */
try {
server.start();
server.join();
}
catch(Exception e) {
println("Could not start http server. Reason: " + e.toString());
};
}
void printCard(String mtext) {
println("Printing card with text: " + mtext);
}
Your PostHandler could look something like this:
public class PostHandler extends AbstractHandler
{
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text/html;charset=utf-8");
String stringParameter = request.getParameter("string");
/* Check if the string parameter is there and not empty */
if (stringParameter != null && !stringParameter.trim().equals("")) {
response.setStatus(HttpServletResponse.SC_OK);
baseRequest.setHandled(true);
response.getWriter().println("<h1>You sent me: " + stringParameter + "</h1>");
println("Received a string via /post: " + stringParameter);
printCard(stringParameter);
}
else {
// Parameter is missing
response.setStatus(HttpServletResponse.SC_BAD_REQUEST );
baseRequest.setHandled(true);
response.getWriter().println("<h1>Error: Missing string parameter</h1>");
println("Missing string via /post.");
}
}
}