Results 1 to 1 of 1
- 11-06-2011, 09:27 AM #1
Member
- Join Date
- Nov 2011
- Posts
- 1
- Rep Power
- 0
ERROR WHILE USING HttpClient CLASS
Hi all,
I am trying to POST an XML to php based Web Service via HTTP POST method. The php form of the target system is something like this :
PHP Code:<?php $xmlstring = '<?xml version="1.0" ?>'; $xmlstring .= '<data>'; $xmlstring .= '<ordernum>1234567890123</ordernum>'; $xmlstring .= '<custname>RUSDY AB. AZIZ</custname>'; $xmlstring .= '<mobilenum>0136130702</mobilenum>'; $xmlstring .= '<orderstatus>OnHold</orderstatus>'; $xmlstring .= '<prodtype>STX</prodtype>'; $xmlstring .= '</data>'; ?> <form name="icp2swans" method="POST" action="http://n9.intra.tm/swans/openapi/icpwaiters.php"> <!--- <form name="icp2swans" method="POST" action="icpwaiters.php"> ---> <!--- <input type="hidden" name="secretkey" value="ef6bf191c37ff1a78633dca0434ef147"> ---> <p>XML Text :</p> <!--- <input type="text" name="ordernum" value="123456789012345" size="15"><br> ---> <textarea name="xmldata" rows="10" cols="100"><?php echo $xmlstring; ?></textarea> <p><input type="submit" value="Submit"></p> </form>
My java code is that doe the POST action is something like this:
The XML that is to be sent is :Java Code:import java.util.Map; import java.util.Set; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; import org.apache.commons.httpclient.UsernamePasswordCredentials; import org.apache.commons.httpclient.auth.AuthScope; import org.apache.commons.httpclient.methods.InputStreamRequestEntity; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.RequestEntity; import org.apache.commons.httpclient.params.HttpClientParams; import org.apache.commons.io.IOUtils; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import com.accenture.eai.arch.DataModel.DataPipe; import com.accenture.eai.arch.DataModel.FlowControlData; import com.tm.hsbb.eai.archcomp.common.constant.HSBBConstant; import com.tm.hsbb.eai.archcomp.common.constant.HSBBErrorCode; import com.tm.hsbb.eai.archcomp.exception.ApplicationRuntimeException; import com.tm.hsbb.eai.archcomp.exception.InternalErrorRuntimeException; import com.tm.hsbb.eai.archcomp.transformer.CdmTransformer; import com.tm.hsbb.eai.common.util.StringUtil; import com.tm.hsbb.eai.commonservices.audit.HSBBAuditLogger; /** * Supports following HTTP features: * - Authentication (AuthScope not well implemented though) * - timeout * @author */ public class HttpMessageSender implements MessageSender { static final Logger logger = Logger.getLogger(HttpMessageSender.class); static Logger perfLogger = Logger.getLogger("EAIPerformanceLogger."+HttpMessageSender.class); @Autowired private HSBBAuditLogger hsbbAuditLogger; private CdmTransformer cdmTransformer; private String webServerUrl; // Mandatory field private String contentType; // Optional field private String username; // Optional field private String password; // Optional field protected String timeOutInMS = "300000"; // Optional field private Map<String, String> requestHeaders; // Optional field // private static MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); public void setRequestHeaders(Map<String, String> requestHeaders) { this.requestHeaders = requestHeaders; } /** * Authentication Schemes supported * - Basic * - Digest * - NTLM (not tested yet!) */ public String send(String inputMsg) { String whatIstheInputMSG = inputMsg; logger.info("Executing HttpMessageSender.send()"); logger.debug("HTTP Message Body: " + inputMsg); logger.debug("Sending to URL: " + webServerUrl); perfLogger.debug("[Enter send()] " + ((perfLogger.isDebugEnabled())?("["+Runtime.getRuntime().freeMemory()+"]"):"")); // HttpClient client = new HttpClient(connectionManager); HttpClient client = new HttpClient(); // Setting the default HTTP POST content type if (StringUtil.isNullOrBlank(contentType)) { contentType = "text/xml; charset=UTF-8"; } // Create HTTP post object PostMethod post = new PostMethod(webServerUrl); // Set HTTP Request Headers (if available) if(requestHeaders!= null) { Set<String> reqHeadersKeySet = (Set<String>)requestHeaders.keySet(); for(String reqHeadersKey : reqHeadersKeySet) { post.setRequestHeader(reqHeadersKey, requestHeaders.get(reqHeadersKey)); } } // Request body content will be retrieved directly from the inputMsg RequestEntity entity = new InputStreamRequestEntity(IOUtils.toInputStream(inputMsg), contentType); post.setRequestEntity(entity); // Set timeout parameter (if available) // Assumption: value is a valid positive number if set if (!StringUtil.isNullOrBlank(timeOutInMS)) { client.getParams().setParameter(HttpClientParams.SO_TIMEOUT, new Integer( timeOutInMS )); } // Set authentication information (if available) if (!StringUtil.isNullOrBlank(username)) { // Pass the credentials to HttpClient. // AuthScope.ANY means that we will send this login credential to any host/url we define (not recommended). client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); post.setDoAuthentication(true); } // Execute request try { int statusCode = client.executeMethod(post); if (statusCode != HttpStatus.SC_OK) { logger.debug("Method failed: " + post.getStatusLine()); throw new InternalErrorRuntimeException("Error while doing HTTP Post with reason: " + post.getStatusLine() + ". and error message is:" + post.getResponseBodyAsString()); } handlePostReturn(post); String httpResponse = post.getResponseBodyAsString(); logger.debug("HTTP Response Status Code: " + statusCode); logger.debug("HTTP Response Body: " + httpResponse); perfLogger.debug("[Exit send()] " + ((perfLogger.isDebugEnabled())?("["+Runtime.getRuntime().freeMemory()+"]"):"")); return httpResponse; } catch (Exception e) { logger.error("Exception occured while sending HTTP POST request to " + webServerUrl , e); throw new ApplicationRuntimeException("post to:"+ webServerUrl + " error! "+e.getMessage(), e, HSBBErrorCode.MESSAGE_INTO_TARGET_HTTP_FAILED, inputMsg); } finally { // Release current connection to the connection pool post.releaseConnection(); } } protected void handlePostReturn(PostMethod post) { // TODO Auto-generated method stub // This is to be overriden } public DataPipe sendWithCdmControlData(DataPipe dataPipe) { String messageBodyToSend = (String)dataPipe.get(FlowControlData.Data); String beName = (String)dataPipe.get(FlowControlData.EventName); String intgMesgId = (String)dataPipe.get(FlowControlData.IntegrationId); this.hsbbAuditLogger.auditLog(HSBBConstant.AUDIT_TYPE_HTTP_REQUEST, messageBodyToSend, beName, intgMesgId, null); String httpResponse = send(messageBodyToSend); this.hsbbAuditLogger.auditLog(HSBBConstant.AUDIT_TYPE_HTTP_RESPONSE, httpResponse, beName, intgMesgId, null); dataPipe.put(FlowControlData.Data, httpResponse); return dataPipe; } public void setCdmTransformer(CdmTransformer cdmTransformer) { this.cdmTransformer = cdmTransformer; } public void setWebServerUrl(String webServerUrl) { this.webServerUrl = webServerUrl; } public void setContentType(String contentType) { this.contentType = contentType; } public void setUsername(String username) { this.username = username; } public void setPassword(String password) { this.password = password; } public void setTimeOutInMS(String timeOutInMS) { this.timeOutInMS = timeOutInMS; } public String getWebServerUrl() { return webServerUrl; } public String getTimeOutInMS() { return timeOutInMS; } }
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<data>
<ordernum>1-J0K0Y</ordernum>
<custname>Ashwaq</custname>
<mobilenum>0125598693</mobilenum>
<orderstatus>Submitted</orderstatus>
<prodtype>DEL</prodtype>
</data>
The problem is that the programme does send the XML to the target system, however the target is returning a result that is indicates an error;
<?xml version="1.0" ?>
<data>
<errorcode>1</errorcode>
<errormsg>XML text was Empty. Sorry, you have submitted an empty form</errormsg>
</data>
According to the administrator of the target system, the error is due to the fact that the something in my HTTP message(the envelope must I presume) must conform to the name attribute of the textarea element in his php form. He even gave me a fragment of his code:
Input name: “xmldata”Java Code:if( isset($_POST['xmldata']) && !empty($_POST['xmldata']) ) { // proceed } else { // return error (is empty) }
This is the first time I am working with a code that requires me to interface with a php based system. I don't even know what I assumed above is correct. Please help. Thank you all in advance.
Similar Threads
-
Eclipse Compile Error: Call validateValue(Class<T>, String, Object, Class<?>...)
By Tomshi in forum EclipseReplies: 0Last Post: 03-27-2011, 05:49 AM -
logging into website using httpclient
By brianfroelund in forum Advanced JavaReplies: 0Last Post: 01-26-2011, 02:55 PM -
Using HttpClient
By jdetloff in forum New To JavaReplies: 4Last Post: 01-06-2010, 10:43 AM -
Using HttpClient with Eclipse
By jdetloff in forum EclipseReplies: 4Last Post: 01-06-2010, 09:47 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks