Extract SOAP custom header information - web-services

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

Related

How to apply Interceptor(Schema validation) to a specific endpoint among multiple services deployed on server

I have two soap end points(soap services) deployed in one server. When i override the following interceptor, it is applying to both services. How to enable/disable the interceptor specific to one service. Kindly help
The interceptor code as follows.
#Override
public void addInterceptors(List<EndpointInterceptor> interceptors) {
PayloadValidatingInterceptor validatingInterceptor = new PayloadValidatingInterceptor();
validatingInterceptor.setValidateRequest(true);
validatingInterceptor.setValidateResponse(true);
validatingInterceptor.setXsdSchemaCollection(LogAnalyzerFile());
interceptors.add(validatingInterceptor);
}
Note: Its an spring boot project, using annotations.
I
package com.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.StringUtils;
import org.springframework.ws.WebServiceMessage;
import org.springframework.ws.config.annotation.EnableWs;
import org.springframework.ws.config.annotation.WsConfigurationSupport;
import org.springframework.ws.context.MessageContext;
import org.springframework.ws.server.SmartEndpointInterceptor;
import org.springframework.ws.server.endpoint.MethodEndpoint;
import org.springframework.ws.soap.SoapBody;
import org.springframework.ws.soap.SoapHeader;
import org.springframework.ws.soap.SoapMessage;
import org.springframework.ws.transport.http.MessageDispatcherServlet;
import org.springframework.ws.wsdl.wsdl11.SimpleWsdl11Definition;
import org.springframework.ws.wsdl.wsdl11.Wsdl11Definition;
import org.springframework.xml.xsd.SimpleXsdSchema;
import org.springframework.xml.xsd.XsdSchema;
import org.xml.sax.SAXException;
import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMResult;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
#EnableWs
#Configuration
public class TestConfig extends WsConfigurationSupport implements SmartEndpointInterceptor {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
#Bean(name="testlog")
public ServletRegistrationBean testlog(ApplicationContext applicationContext) {
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setApplicationContext(applicationContext);
servlet.setTransformWsdlLocations(true);
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(servlet, "/File/*");
servletRegistrationBean.setName("Log");
return servletRegistrationBean;
}
#Bean(name = "testFile")
public Wsdl11Definition testFile()
{
SimpleWsdl11Definition wsdl11Definition = new SimpleWsdl11Definition();
wsdl11Definition.setWsdl(new ClassPathResource("test.wsdl"));
logger.info("test.wsdl:");
return wsdl11Definition;
}
#Bean(name = "UploadLogFile")
public XsdSchema UploadLogFile() {
return new SimpleXsdSchema(new ClassPathResource("1.xsd"));
}
#Bean(name = "ErrorInfo")
public XsdSchema ErrorInfo() {
return new SimpleXsdSchema(new ClassPathResource("2.xsd"));
}
public Resource[] getSchemas() {
List<Resource> schemaResources = new ArrayList<>();
schemaResources.add(new ClassPathResource("1.xsd"));
schemaResources.add(new ClassPathResource("2.xsd"));
return schemaResources.toArray(new Resource[schemaResources.size()]);
}
#Override
public boolean shouldIntercept(MessageContext messageContext, Object endpoint) {
if (endpoint instanceof MethodEndpoint) {
MethodEndpoint methodEndpoint = (MethodEndpoint)endpoint;
return methodEndpoint.getMethod().getDeclaringClass() == YourEndpoint.class;
}
return false;
}
private Boolean validateSchema(Source source_, MessageContext messageContext) throws Exception {
boolean errorFlag = true;
SchemaFactory _schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema _schema = _schemaFactory.newSchema(getSchemas()[0].getFile());
Validator _validator = _schema.newValidator();
DOMResult _result = new DOMResult();
try {
_validator.validate(source_, _result);
} catch (SAXException _exception) {
errorFlag = false;
SoapMessage response = (SoapMessage) messageContext.getResponse();
String faultString = StringUtils.hasLength(_exception.getMessage()) ? _exception.getMessage() : _exception.toString();
SoapBody body = response.getSoapBody();
body.addServerOrReceiverFault(faultString, Locale.US);
_exception.printStackTrace();
}
return errorFlag;
}
#Override
public boolean handleRequest(MessageContext messageContext, Object endpoint) throws Exception {
WebServiceMessage webServiceMessageRequest = messageContext.getRequest();
SoapMessage soapMessage = (SoapMessage) webServiceMessageRequest;
SoapHeader soapHeader = soapMessage.getSoapHeader();
Source bodySource = soapMessage.getSoapBody().getPayloadSource();
return validateSchema(bodySource,messageContext);
}
#Override
public boolean handleResponse(MessageContext messageContext, Object endpoint) throws Exception {
return true;
}
#Override
public boolean handleFault(MessageContext messageContext, Object endpoint) throws Exception {
return false;
}
#Override
public void afterCompletion(MessageContext messageContext, Object endpoint, Exception ex) throws Exception {
}
}

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}")

How to convert SOAP request and response in XML format?

I've set up a SOAP WebServiceProvider in JAX-WS, but I'm having trouble figuring out how to get request and response in XML format from a SOAP request and response. Here's a sample of the code I've got right now, and where I'm trying to grab the XML:
package com.ewb.socialbanking.creditcardMain;
import org.springframework.ws.client.core.support.WebServiceGatewaySupport;
import org.springframework.ws.soap.client.core.SoapActionCallback;
import com.ewb.socialbanking.creditcardws.GetCcNumber;
import com.ewb.socialbanking.creditcardws.GetCcNumberResponse;
import com.safenet.wsdl.LoginUser;
/*THIS IS HOW I AM GIVING THE REQUEST :
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(CreditCardConfig.class);
ctx.refresh();
CreditCardClient cCClient = ctx.getBean(CreditCardClient.class);
GetCcNumber cCNumber = new GetCcNumber();
ObjectFactory enrollObjFactory = new ObjectFactory();
cCNumber.setT24Cif(enrollObjFactory.createString("abc"));
cCNumber.setLinkId(enrollObjFactory.createString("def"));
cCNumber.setCcCif(enrollObjFactory.createString("ghi"));
cCNumber.setMsgRefNo(enrollObjFactory.createString("jkl"));
GetCcNumberResponse valueForRes = cCClient.getCreditCardDetails(cCNumber);*/
public class CreditCardClient extends WebServiceGatewaySupport {
public GetCcNumberResponse getCreditCardDetails(GetCcNumber request) {
//I want here request in xml format??
System.out.println("req : "+request);
//Right now it is coming as :
//req : com.ewb.socialbanking.creditcardws.GetCcNumber#5d534f5d
GetCcNumberResponse response = null;
try {
response = (GetCcNumberResponse) getWebServiceTemplate()
.marshalSendAndReceive(
request,
new SoapActionCallback(
"http://F9M9MV1RENTAL:8088/mocksoap/GetCcNumber"));
} catch (Exception e) {
e.printStackTrace();
}
//I want here response in xml format??
System.out.println("res : "+response);
//Right now it is coming as :
//res : com.ewb.socialbanking.creditcardws.GetCcNumberResponse#514646ef
return response;
}
}
JAX-WS services return JAXB objects. If you want to marshall that object to an outputstream, you simply use the JAXB API.
Marshaller m = JAXBContext.newInstance(GetCcNumberResponse.class).createMarshaller();
m.marshal(response, System.out);
I've tried by my self, and it works. If you want to get the SOAP message, a good way to do it is using a handler at server side. The following is my handler.
package com.documentType.handler;
import java.io.IOException;
import java.util.Set;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPException;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
public class TestHandler implements SOAPHandler<SOAPMessageContext> {
#Override
public void close(MessageContext arg0) {
// TODO Auto-generated method stub
}
#Override
public boolean handleFault(SOAPMessageContext arg0) {
// TODO Auto-generated method stub
return false;
}
// this method will be called twice (in and out)
#Override
public boolean handleMessage(SOAPMessageContext context) {
// true if the msg is going out
Boolean outBoundMsg = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
try {
if (outBoundMsg) {
System.out.println("this is response");
context.getMessage().writeTo(System.out);
} else {
System.out.println("this is request");
context.getMessage().writeTo(System.out);
}
} catch (SOAPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
#Override
public Set<QName> getHeaders() {
// TODO Auto-generated method stub
return null;
}
}
The output in console is as the following
this is request
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Header/><S:Body><ns2:echo xmlns:ns2="http://ws.documentType.com/"><arg0>yoyoyo</arg0></ns2:echo></S:Body></S:Envelope>
this is response
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Body><ns2:echoResponse xmlns:ns2="http://ws.documentType.com/"><return>echo: yoyoyo</return></ns2:echoResponse></S:Body></S:Envelope>
If you have difficulty to add a handler, follow the following tutorial
http://www.mkyong.com/webservices/jax-ws/jax-ws-soap-handler-in-server-side/
http://www.mkyong.com/webservices/jax-ws/jax-ws-soap-handler-in-client-side/
http://www.mkyong.com/webservices/jax-ws/jax-ws-soap-handler-testing-for-client-and-server-side/

Adding username and password to soap header in Java by using PasswordText Type and axis2

I want to add username and password to soap header in java by using PasswordText Type and axis2.
Code snippet I use
public static void WSSPasswordAuthentication(org.apache.axis2.client.ServiceClient client, String endPointUrl, String username, String password) throws CSException{
OMFactory omFactory = OMAbstractFactory.getOMFactory();
OMElement omSecurityElement = omFactory.createOMElement(new QName( "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Security", "wsse"), null);
OMElement omusertoken = omFactory.createOMElement(new QName("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "UsernameToken","wsse"), null);
OMElement omuserName = omFactory.createOMElement(new QName("", "Username", "wsse"), null);
omuserName.setText(username);
OMElement omPassword = omFactory.createOMElement(new QName("", "Password", "wsse"), null);
omPassword.addAttribute("Type","http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText",null );
omPassword.setText(password);
omusertoken.addChild(omuserName);
omusertoken.addChild(omPassword);
omSecurityElement.addChild(omusertoken);
client.addHeader(omSecurityElement);
}
And resultant header :
<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"><wsu:UsernameToken xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"><Username>erapor</Username><Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">erapor</Password></wsu:UsernameToken></wsse:Security>
But
The header I want : <soapenv:Header><wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"><wsse:UsernameToken xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"><wsse:Username>erapor</wsse:Username><wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">erapor</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header>
Otherwise I couldn't use the header
How can I modify?
You can use plain JAXWS if you have an option to resolve this instead of using AXIS2 on the client side. This is generic and easy to add these kind of security headers.
In your JDK 6.0 HOME (This example works only from JDK 6.0 and above)
jdk1.6.0_26\bin\wsimport is an utility available
You can create the stub using the wsimport utility
wsimport -keep -verbose http://localhost:8080/<WebserviceName>/services/<WebserviceName>?wsdl
Create a message handler
MessageHandler.java
package com.secure.client;
import java.util.Set;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPHeader;
import javax.xml.ws.WebServiceException;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
public class MessageHandler implements SOAPHandler<SOAPMessageContext>{
#Override
public void close(MessageContext arg0) {
// TODO Auto-generated method stub
}
#Override
public Set getHeaders() {
// TODO Auto-generated method stub
return null;
}
#Override
public boolean handleFault(SOAPMessageContext context) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean handleMessage(SOAPMessageContext soapMessageContext) {
try {
boolean outMessageIndicator = (Boolean) soapMessageContext
.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (outMessageIndicator) {
SOAPEnvelope envelope = soapMessageContext.getMessage().getSOAPPart().getEnvelope();
SOAPHeader header = envelope.addHeader();
SOAPElement security = header.addChildElement("Security", "wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
SOAPElement usernameToken = security.addChildElement("UsernameToken", "wsse");
usernameToken.addAttribute(new QName("xmlns:wsu"), "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
SOAPElement username = usernameToken.addChildElement("Username", "wsse");
username.addTextNode("wsuser");
SOAPElement password = usernameToken.addChildElement("Password", "wsse");
password.setAttribute("Type", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText");
password.addTextNode("wspwd");
}
} catch (Exception ex) {
throw new WebServiceException(ex);
}
return true;
}
}
Create HeaderHandlerResolver.java
package com.secure.client;
import java.util.ArrayList;
import java.util.List;
import javax.xml.ws.handler.Handler;
import javax.xml.ws.handler.HandlerResolver;
import javax.xml.ws.handler.PortInfo;
public class HeaderHandlerResolver implements HandlerResolver {
#SuppressWarnings("unchecked")
public List<Handler> getHandlerChain(PortInfo portInfo) {
List<Handler> handlerChain = new ArrayList<Handler>();
MessageHandler hh = new MessageHandler();
handlerChain.add(hh);
return handlerChain;
}
}
You can create the client code using stub
Client.java
import javax.xml.ws.BindingProvider;
import com.secure.HelloService;
import com.secure.HelloServiceException;
import com.secure.HelloServicePortType;
public class Client {
public static void main(String[] args) {
HelloService service = new HelloService();
service.setHandlerResolver(new HeaderHandlerResolver());
HelloServicePortType port = service.getHelloServiceHttpSoap11Endpoint();
// Use the BindingProvider's context to set the endpoint
BindingProvider bp = (BindingProvider)port;
bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "http://localhost:8080/<WebserviceName>/services/<WebserviceName>");
System.out.println(port.getVersion());
try {
System.out.println(port.getHello("Zack"));
} catch (HelloServiceException e) {
e.printStackTrace();
}
}
}

Using cookies from httpclient in webview

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