HttpUrlConnection.connect() Query - httpurlconnection

After hours of trawling the internet and trying to make sense of the documentation I seem unable to find a resolution to this problem.
I have an application which is using an ASyncTask to connect to a server I have 3 addresses to "test" the connection.
Now the problem is when I use the Myconnection.connect() the background task just hangs if there is either no known address or a dead link.
How can I test this connection when with a dead link or dead server it hangs and does not receive any response
The errors in the Logcat are
07-02 12:47:13.101 13850-20562/nodomain.myapplication D/URL ERRORhttp://10.0.0.2/testdb/connection.php
07-02 12:47:13.339 13850-20562/nodomain.myapplication I/URL IS OK: [ 07-02 12:47:13.339 13850:20562 I/ ]Status : 200
07-02 12:47:13.344 13850-20562/nodomain.myapplication D/URL ERRORhttp://localhost/myPage.php
As you can see the only URL I get a response from is www.google.com
My code is below:
package nodomain.myapplication;
import android.os.AsyncTask;
import android.util.Log;
import org.w3c.dom.Text;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
/**
* Created by Shab on 02/07/2017.
*/
public class bgWorker extends AsyncTask<Void, Integer, Void> {
#Override
protected Void doInBackground(Void... params)
{
String db_Username = "root";
String db_Password = "";
String db_Name = "testdb";
String url1 = "http://10.0.0.2/testdb/connection.php"; //DEAD? (NO RESPONSE)
(Program Hang until exception is called)
String url2 = "http://www.google.com"; //OK RESPONSE 200
String url3 = "http://localhost/myPage.php"; //NO RESPONSE
try {
getResponseCodes(url1);
getResponseCodes(url2);
getResponseCodes(url3);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
}
private String encodeURLString(String value) {
String encodedString = "";
try {
encodedString = URLEncoder.encode(value, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return encodedString;
}
public static int getResponseCodes(String TheURL) throws MalformedURLException,IOException
{
URL oUrl = new URL(TheURL);
HttpURLConnection oHuC = (HttpURLConnection) oUrl.openConnection();
oHuC.setRequestMethod("HEAD");
int response = 0;
try{
oHuC.connect();
response = oHuC.getResponseCode();
if(response == 200)
{
Log.i("URL IS OK","");
}else{
Log.i("URL IS NOT OK","");
}
Log.i("", "Status : " + response);
}catch(IOException e){
Log.d("URL ERROR" + oUrl, "D");
}
return response;
}
}
Even with the IF statement testing the response for a 200 OK it only manages to interpret one response from the 3 URL due to the URL IS OK output.

Related

Vertx JWKS/JWT verification throws a 500 with no errors logged

I have a very basic Vertx demo I'm trying to create that fetches a JWK from an endpoint and creates an RSAPublicKey for verifying a JWT signature:
package example;
import com.auth0.jwk.JwkException;
import com.auth0.jwk.JwkProvider;
import com.auth0.jwt.interfaces.DecodedJWT;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.http.HttpServer;
import io.vertx.ext.web.Router;
import com.auth0.jwk.UrlJwkProvider;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.interfaces.RSAPublicKey;
import com.auth0.jwt.interfaces.RSAKeyProvider;
import java.security.interfaces.RSAPrivateKey;
public class MainVerticle extends AbstractVerticle {
#Override
public void start(Promise<Void> startPromise) throws Exception {
HttpServer server = vertx.createHttpServer();
Router router = Router.router(vertx);
router.route().handler(routingContext -> {
String authHeader = routingContext.request().getHeader("Authorization");
// pull token from header
String token = authHeader.split(" ")[1];
URL jwksEndpoint = null;
try {
jwksEndpoint = new URL("http://localhost:1080/jwks");
} catch (MalformedURLException e) {
e.printStackTrace();
}
JwkProvider jwkProvider = new UrlJwkProvider(jwksEndpoint);
RSAKeyProvider keyProvider = new RSAKeyProvider() {
#Override
public RSAPublicKey getPublicKeyById(String kid) {
//Received 'kid' value might be null if it wasn't defined in the Token's header
RSAPublicKey publicKey = null;
try {
publicKey = (RSAPublicKey) jwkProvider.get(kid).getPublicKey();
} catch (JwkException e) {
e.printStackTrace();
}
return publicKey;
}
#Override
public RSAPrivateKey getPrivateKey() {
return null;
}
#Override
public String getPrivateKeyId() {
return null;
}
};
Algorithm algorithm = Algorithm.RSA256(keyProvider);
JWTVerifier verifier = JWT.require(algorithm)
.withIssuer("auth0")
.build();
DecodedJWT jwt = verifier.verify(token);
System.out.println(jwt);
routingContext.next();
});
router.route("/hello").handler(ctx -> {
ctx.response()
.putHeader("content-type", "text/html")
.end("<h1>Hello from non-clustered messenger example!</h1>");
});
server.requestHandler(router).listen(8888, http -> {
if(http.succeeded()) {
startPromise.complete();
System.out.println("HTTP server started on port 8888");
} else {
startPromise.fail(http.cause());
}
});
}
}
The problem is that when I make request to the /hello endpoint, the application immediately returns a 500. But nothing appears in the logs (even at debug level).
I've tried manually specifying the kid property to rule out the jwkProvider not returning properly
I'm at a loss at how to gain any more insight into what is failing.
Turns out to completely be my oversight. Wrapping that verifier.verify() call in a try/catch showed me that I was expecting an issuer. This is the same problem I was having while trying to achieve this in Quarkus! I was able to remove that from the builder and now this works perfectly.

My Post Request returns a 500 internal server error in Jersey

I am trying to post data in Jersey but all I get is a 500 error. My GET requests are all working fine.
Below is my client code.
package main;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
public class MainClass {
public static void main(String[] args) {
try {
Client client = Client.create();
client.addFilter(new HTTPBasicAuthFilter("admin", "admin"));
WebResource webResource = client
.resource("http://localhost:7307/mysite/rest_service/postdataclass/postData");
String input = "{\"name\":\"Violent Soho\",\"last\":\"Jesus Stole My Girlfriend\"}";
ClientResponse response = webResource.type("application/json")
.post(ClientResponse.class, input);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
System.out.println("Output from Server .... \n");
String output = response.getEntity(String.class);
System.out.println(output);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
And Here is my other class
package service.utils;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import beans.AASample;
#Path("postdataclass")
public class PostSample {
#GET
#Path("/sayHell")
public Response sayHell() {
return Response.status(Response.Status.OK).entity("Hell").build();
}
#POST
#Path("/postData")
#Consumes(MediaType.APPLICATION_JSON)
public Response postData(AASample sample) {
return Response.status(Response.Status.OK).entity("Profile " + sample.toString()).build();
}
}
And my AAClass
package beans;
public class AASample {
private String name;
private String last;
public AASample(String name, String last) {
super();
this.name = name;
this.last = last;
}
public AASample() {
super();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLast() {
return last;
}
public void setLast(String last) {
this.last = last;
}
#Override
public String toString() {
return "AASample [name=" + name + ", last=" + last + "]";
}
}
Below is the Server Log when I Make the Post Request.
Jul 08, 2016 8:35:22 PM org.glassfish.jersey.filter.LoggingFilter log
INFO: 3 * Server has received a request on thread http-nio-8090-exec-4
3 > POST http://localhost:8090/mysite/rest_service/postdataclass/postData
3 > accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
3 > authorization: Basic YWRtaW46YWRtaW4=
3 > connection: keep-alive
3 > content-length: 43
3 > content-type: application/json
3 > host: localhost:8090
3 > user-agent: Java/1.8.0_20
Jul 08, 2016 8:35:23 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [Spot Buddy Service] in context with path [/mysite] threw exception [org.glassfish.jersey.server.ContainerException: java.lang.AbstractMethodError: com.fasterxml.jackson.jaxrs.base.ProviderBase._configForReading(Lcom/fasterxml/jackson/databind/ObjectMapper;[Ljava/lang/annotation/Annotation;)Lcom/fasterxml/jackson/jaxrs/cfg/EndpointConfigBase;] with root cause
java.lang.AbstractMethodError: com.fasterxml.jackson.jaxrs.base.ProviderBase._configForReading(Lcom/fasterxml/jackson/databind/ObjectMapper;[Ljava/lang/annotation/Annotation;)Lcom/fasterxml/jackson/jaxrs/cfg/EndpointConfigBase;
at com.fasterxml.jackson.jaxrs.base.ProviderBase.readFrom(ProviderBase.java:644)
at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.invokeReadFrom(ReaderInterceptorExecutor.java:260)
at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.aroundReadFrom(ReaderInterceptorExecutor.java:236)
I converted my data to a json object manually. changed post method to
#POST
#Path("/postData")
#Consumes(MediaType.APPLICATION_JSON)
public Response postData(String sample) {
AASample object = StringToObjectConverter.getObject(sample);
if(object != null){
return Response.status(Response.Status.OK).entity("Object " + object.toString()).build();
}else{
return Response.status(Response.Status.OK).entity("We Failed Decoding :" + sample +":").build();
}
}
StringToObjectConverter class
package main
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import beans.AASample;
public class StringToObjectConverter {
public static AASample getObject(String postedData) {
AASample aaSample = null;
ObjectMapper mapper = new ObjectMapper();
try {
aaSample = mapper.readValue(postedData, AASample.class);
} catch (JsonGenerationException e) {
aaSample = null;
} catch (JsonMappingException e) {
aaSample = null;
} catch (IOException e) {
aaSample = null;
}
return aaSample;
}
}

Raspberry PI Tomcat7 and Serial Port Communication using ISO8859-7

I am trying to relay a message from a Servlet to COM in raspberry pi on Tomcat 7.
I am using null cable between raspberry and my PCs to test.
I am using jssc API (Java Simple Serial Connector) for serial communication.
Raspberry pi is using JDK 1.8.0_65.
I am getting the message in UTF8 and I should output it in ISO8859-7.
Since UTF8 is a superset of ISO8859-7, the app that calls the servlet ensures all characters sent are legitimate for ISO8859-7.
My code:
package com.test.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import jssc.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet(value = "/Relay", name = "Relay")
public class Relay extends HttpServlet {
static Logger app = null;
static {
app = Logger.getLogger("com.test.app");
}
protected void doGet(HttpServletRequest request,HttpServletResponse response) {
doPost(request, response);
}
protected void doPost(HttpServletRequest request,HttpServletResponse response) {
try {
request.setCharacterEncoding("ISO-8859-7");;
response.setCharacterEncoding("ISO-8859-7");
//request.setCharacterEncoding("UTF-8");
//response.setCharacterEncoding("UTF-8")
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String message = request.getParameter("message");
app.logp(Level.INFO, this.getClass().getCanonicalName(),"APP", message);
String[] portNames = SerialPortList.getPortNames();
app.logp(Level.INFO, this.getClass().getCanonicalName(),"APP", portNames.length+"");
for(int i = 0; i < portNames.length; i++){
applogp(Level.INFO, this.getClass().getCanonicalName(),"APP", portNames[i]);
byte[] msg = new byte[1024];
msg = message.getBytes("ISO-8859-7");
Charset utf8charset = Charset.forName("UTF-8");
Charset iso88597charset = Charset.forName("ISO-8859-7");
ByteBuffer inputBuffer = ByteBuffer.wrap(message.getBytes());
CharBuffer data = utf8charset.decode(inputBuffer);
ByteBuffer outputBuffer = iso88597charset.encode(data);
byte[] outputData = outputBuffer.array();
byte[] b1 = message.getBytes();
byte[] b2 = message.getBytes(Charset.forName("ISO-8859-7"));
byte[] b3 = message.getBytes(StandardCharsets.ISO_8859_1);
SerialPort serialPort = new SerialPort((portNames[i]));
try {
serialPort.openPort();
serialPort.setParams(SerialPort.BAUDRATE_9600,SerialPort.DATABITS_8, SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
serialPort.writeBytes(msg);
serialPort.writeBytes(message.getBytes());
serialPort.writeBytes(outputData);
serialPort.writeBytes(b1);
serialPort.writeBytes(b2);
serialPort.writeBytes(b3);
serialPort.closePort();
} catch (SerialPortException ex) {
app.logp(Level.INFO, this.getClass().getCanonicalName(),"APP", ex.getMessage());
out.write("NOK");
out.close();
}
}
out.write("OK");
out.close();
} catch (IOException e) {
app.logp(Level.INFO, this.getClass().getCanonicalName(),"APP", e.getMessage());
}
}
private static final long serialVersionUID = 1L;
}
The problem is that when I am testing I do not get valid output in putty.
putty output
I have configured putty to display ISO8859-7 characters.
Any for changes ?
What am I missing ?
Thanks in advance.
I tried to divide the problem by producing the following code:
import java.io.UnsupportedEncodingException;
import jssc.SerialPort;
import jssc.SerialPortException;
public class SerialTest {
public static void main(String[] args) {
String message = "message μήνυμα";
if ( sendTextOnCom(message) ) {
System.out.println("SUCCESS MESSAGE SENT");
}
else{
System.out.println("FAIL MESSAGE NOT SENT");
}
}
private static boolean sendTextOnCom(String message) {
boolean isOverlaid = false;
SerialPort com = null;
try {
String comNo = "COM1"; // String comNo="/dev/ttyUSB0"; //when used in Raspberry
com = new SerialPort(comNo);
com.openPort();
com.setParams(9600, 8, 1, 0);
com.writeString(message);
com.writeBytes(message.getBytes("ISO-8859-7"));
com.closePort();
isOverlaid = true;
}
catch (SerialPortException ex) {
System.out.println("[ERROR] COM ERROR SENDING MESSAGE");
isOverlaid = false;
try {
com.closePort();
} catch (SerialPortException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return isOverlaid;
}
}
The code is working normally in Windows 7 64bit and it is producing output in putty with the right characters.
When I compile and run the same code in raspberry PI the output in putty is not showing the valid characters.
I tend to think that it's a raspberry PI configuration issue.

Log request xml on error at OutFaultInterceptor for CXF Web Service

Is it possible to retrieve and log the request XML to a file at OutFaultInterceptor when I hit an error such as fail schema validation?
I have tried search the web but don't seems to be able to find much related to this.
Yest it is possible. I have wrote CxfOutInterceptor for getting XML of the message. Here is the code:
import org.apache.cxf.common.util.StringUtils;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.io.CacheAndWriteOutputStream;
import org.apache.cxf.io.CachedOutputStream;
import org.apache.cxf.io.CachedOutputStreamCallback;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CxfOutInterceptor extends AbstractPhaseInterceptor<Message> {
private static final Logger LOGGER = LoggerFactory.getLogger(CxfInInterceptor.class);
public CxfOutInterceptor() {
super(Phase.PRE_STREAM);
}
public static final String SINGLE_KEY = CxfOutInterceptor.class.getName() + ".Processed";
private static final int LIMIT = 10 * 1024 * 1024;
#Override
public void handleFault(Message message) {
LOGGER.trace("handleFault");
try {
internalHandleMessage(message);
} catch (Throwable ex) {
LOGGER.error("Exception thrown by internalHandleMessage: ", ex);
} finally {
LOGGER.trace("handleFault - end");
}
}
#Override
public void handleMessage(Message message) throws Fault {
LOGGER.trace("handleMessage");
try {
if (onceOnly(message)) {
LOGGER.debug("handled message previously");
return;
}
internalHandleMessage(message);
} finally {
LOGGER.trace("handleMessage - end");
}
}
private class LogCallback implements CachedOutputStreamCallback {
private final Message message;
private final OutputStream origStream;
public LogCallback(final Message msg, final OutputStream os) {
this.message = msg;
this.origStream = os;
}
#Override
public void onFlush(CachedOutputStream cos) {
}
#Override
public void onClose(CachedOutputStream cos) {
StringBuilder requestBuilder = new StringBuilder();
String encoding = (String) message.get(Message.ENCODING);
try {
writePayload(requestBuilder, cos, encoding);
//requestBuilder - is your actuall body of the message.
} catch (IOException ex) {
LOGGER.trace("Unable to write output stream to StringBuilder:\n" + ex.toString());
}
try {
cos.lockOutputStream();
cos.resetOut(null, false);
} catch (Exception ex) {
LOGGER.info("Ignoring exception");
}
message.setContent(OutputStream.class, origStream);
}
}
private void internalHandleMessage(Message message) {
final OutputStream os = message.getContent(OutputStream.class);
final Writer writer = message.getContent(Writer.class);
if (os == null && writer == null) {
return;
}
if (os == null) {
message.setContent(Writer.class, writer);
} else {
final CacheAndWriteOutputStream newOut = new CacheAndWriteOutputStream(os);
message.setContent(OutputStream.class, newOut);
newOut.registerCallback(new LogCallback(message, os));
}
}
private static boolean onceOnly(Message message) {
if (message.getExchange().containsKey(SINGLE_KEY)) {
return true;
} else {
message.getExchange().put(SINGLE_KEY, Boolean.TRUE);
return false;
}
}
private static void writePayload(StringBuilder builder, CachedOutputStream cos, String encoding)
throws IOException {
if (StringUtils.isEmpty(encoding)) {
cos.writeCacheTo(builder, LIMIT);
} else {
cos.writeCacheTo(builder, encoding, LIMIT);
}
}
}
You will get the XML of the message in onClose method. Refer to this comment: //requestBuilder - is your actuall XML of the message.

SSL "Peer not Authenticated" error with HttpClient 4 - works in some case but not others

I have a wildcard cert for *.mydomain.com (the names have been changed to protect the innocent...that is NOT the real domain :) )
When using a correctly implemented Java HttpClient 4 (the issue is not seen in FF), Service calls made via HTTPS to api.mydomain.com are successful where as identical service calls made to non-production subdomains of mydomain.com (developer.mydomain.com, api-beta.mydomain.com, api-uat.mydomain.com) generate this Exception with the Test harness code below:
javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated
at com.sun.net.ssl.internal.ssl.SSLSessionImpl.getPeerCertificates(SSLSessionImpl.java:352)
at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:128)
at org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(SSLSocketFactory.java:397)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:148)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:149)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:121)
at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:573)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:425)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:820)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:754)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:732)
at com.mydomain.httpclientexample.HttpClientTestv2.main(HttpClientTestv2.java:54)
While the SLL cert on developer.mydomain.com, api-beta.mydomain.com & api-uat.mydomain.com appears to be the same WC cert as api.mydomain.com, the exception is not seen on api.mydomain.com but it is on the other sub-domains. The code works on api-na.mydomain.com and should work on the non-production subdomains.
Any ideas?
Client code: As you can see, I can easily change the ADDRESS_VALIDATION_SERVICE_URI I want to call. The api.mydomain.com one works without the SSLPeerUnverifiedException; the other three URIs throw the exception...
package com.mydomain.httpclientexample;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
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 HttpClientTestv2 {
//public final static String ADDRESS_VALIDATION_SERVICE_URI = "https://developer.mydomain.com/v1.0/stores/MYSTORE/address/validate.xml";
public final static String ADDRESS_VALIDATION_SERVICE_URI = "https://api-beta.mydomain.com/v1.0/stores/MYSTORE/address/validate.xml";
//public final static String ADDRESS_VALIDATION_SERVICE_URI = "https://api-uat.mydomain.com/v1.0/stores/MYSTORE/address/validate.xml";
//public final static String ADDRESS_VALIDATION_SERVICE_URI = "https://api.mydomain.com/v1.0/stores/MYSTORE/address/validate.xml";
public final static String APIKEY_ATTRIBUTE_NAME = "apikey";
public final static String APIKEY_ATTRIBUTE_VALUE = "2c90bc83e821364ffa557486c3e2a44e";
/**
* #param args
*/
public static void main(String[] args) {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(ADDRESS_VALIDATION_SERVICE_URI);
System.out.println("executing request" + httpPost.getRequestLine());
//set a request header
httpPost.setHeader(APIKEY_ATTRIBUTE_NAME , APIKEY_ATTRIBUTE_VALUE);
//add the xml body
StringEntity postBody = null;
try {
postBody = new StringEntity(getXMLDoc(),"UTF-8");
} catch (UnsupportedEncodingException uee) {
System.out.println("----------------------------------------");
System.out.println("Exception Caught in UnsupportedEncodingException catch block");
System.out.println("----------------------------------------");
uee.printStackTrace();
}
httpPost.setEntity(postBody);
HttpResponse response;
try {
response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
System.out.println("Content:" + EntityUtils.toString(entity));
EntityUtils.consume(entity);
// entity.consumeContent();
}
} catch (ClientProtocolException e) {
System.out.println("----------------------------------------");
System.out.println("Exception Caught in ClientProtocolException catch block");
System.out.println("----------------------------------------");
e.printStackTrace();
} catch (IOException e) {
System.out.println("----------------------------------------");
System.out.println("Exception Caught in ClientProtocolException catch block");
System.out.println("----------------------------------------");
e.printStackTrace();
}
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
private static String getXMLDoc() {
StringBuffer XMLDoc = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\"?><AddressValidationRequest xmlns=\"http://api.mydomain.com/schema/checkout/1.0\">")
.append("<Header><MaxAddressSuggestions>5</MaxAddressSuggestions></Header>")
.append("<Address><Line1>17243 S. Mill Ln</Line1><Line2/><City>Ocean View</City><MainDivision>DE</MainDivision><CountryCode>US</CountryCode><PostalCode>19970</PostalCode></Address>")
.append("</AddressValidationRequest>");
return XMLDoc.toString();
}
}