本文介绍了与Android HTTP POST问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是下面的code执行HTTP POST请求。该是的PostData以字符串形式

中的PostData样品:

金塔:枪鱼:广频段:1-1:registr通货膨胀业务:丽nkAcquisitionurn:马林:organizat离子:testpdc:德维CE制造商-X:CLIENtnemo:aa08a1:59Ea7e8cfa7a8582http://docs.oasis-open.org/wss/2004/01 /绿洲-200401-WSS-wssecuriTY-公用事业1.0.x的SDURI =金塔:三月林:核心:1.0:NEM○:协议:PROFI乐:1华盛顿州立大学:ID =SIgid0003nemosec:用法=HTTP://ñemo.intertrust.cOM / 2005/10 / SECUR性/配置文件/></ SOAP-ENV:EnveloPE>

我们期待一个XML / SOAP响应,而不是我们得到一个xml文件作为响应。谁能告诉我,如果做一个HTTP POST的程序是正确的(如跌破code)

注:,卷曲用于执行自检工作正常使用时,同样POSTDATA

 公共字节[] SENDRECV(字符串的PostData,长postDataSize){

  尝试{
   如果(!(PostData.equals(空))){
    isPost = TRUE;
    // InputStream的postDataInputStream =新ByteArrayInputStream的(POSTDATA);
    // BasicHttpEntity httpPostEntity =新BasicHttpEntity();
    //httpPostEntity.setContent(postDataInputStream);
    StringEntity httpPostEntity =新StringEntity(的PostData,HTTP.UTF_8);
    //httpPostEntity.setContentLength(postData.length);
    //httpPostEntity.setContentType("application/x-www-form-urlen$c$cd);
    httpPost.setEntity(httpPostEntity);
    httpPost.setHeader(内容长度,新的整数(PostData.length())的toString());
    httpPost.setHeader(内容类型,应用程序/ x-WWW的形式urlen codeD);
    httpPost.setHeader(期望,100-继续);

   }
  }赶上(例外五){
   e.printStackTrace();
  }

  尝试 {
   如果(isPost ==真){
    响应= mAndroidHttpClient.execute(httpPost);
    isPost = FALSE;
   }
   其他 {
    响应= mAndroidHttpClient.execute(HTTPGET);
   }
   。状态code = response.getStatusLine()的getStatus code();

   如果(状态code!= 200){
    如果(状态code == 404){
     //System.out.println("error在HTTP连接:404);

     //返回ERR_HTTP_NOTFOUND
    }否则,如果(状态code == 500){
     //System.out.println("error在HTTP连接:500);
     //返回ERR_HTTP_INTERNALSEVERERROR
    } 其他 {
     //System.out.println("error在HTTP连接:误差未知);
     //返回ERR_HTTP_FATAL
    }
   }

   HttpEntity实体= response.getEntity();
   InputStream的是= entity.getContent();

   ByteArrayOutputStream BOS =新ByteArrayOutputStream();
   为(中间体下一= is.​​read();!下一= ENDOFSTREAM;接下来= is.​​read()){
    bos.write(下);
   }
   responseBuffer = bos.toByteArray();
   bos.flush();
   bos.close();

   }赶上(IOException异常E){
    e.printStackTrace();
    }

   返回responseBuffer;
 }
 

解决方案

//创建XML文件

 的DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
         dbfac.setNamespaceAware(真正的);
         DocumentBuilder的docBuilder = NULL;
         尝试 {
            docBuilder = dbfac.newDocumentBuilder();
        }赶上(的ParserConfigurationException E){
            // TODO自动生成的catch块
            e.printStackTrace();
        }
         DOMImplementation的domImpl = docBuilder.getDOMImplementation();
         文档DOC = domImpl.createDocument(http://coggl.com/InsertTrack,TrackEntry,NULL);
         doc.setXmlVersion(1.0);
         doc.setXmlStandalone(真正的);

         元件trackElement = doc.getDocumentElement();

         元件CompanyId = doc.createElement(CompanyId);
         CompanyId.appendChild(doc.createTextNode(1));
         trackElement.appendChild(CompanyId);

         元件CreatedBy = doc.createElement(CreatedBy);
         CreatedBy.appendChild(doc.createTextNode(6));
         trackElement.appendChild(CreatedBy);

         元件DepartmentID的= doc.createElement(DepartmentID的);
         DepartmentId.appendChild(doc.createTextNode(4));
         trackElement.appendChild(DepartmentID的);

         元件IsBillable = doc.createElement(IsBillable);
         IsBillable.appendChild(doc.createTextNode(1));
         trackElement.appendChild(IsBillable);

         元件ProjectId = doc.createElement(ProjectId);
         ProjectId.appendChild(doc.createTextNode(1));
         trackElement.appendChild(ProjectId);

         元件开始时间= doc.createElement(开始时间);
         StartTime.appendChild(doc.createTextNode(2012年3月14日10点44分45秒));
         trackElement.appendChild(开始时间);

         元件停止时间= doc.createElement(停止时间);
         StopTime.appendChild(doc.createTextNode(2012年3月14日11时44分45秒));
         trackElement.appendChild(停止时间);

         元件的TaskID = doc.createElement(TASKID);
         TaskId.appendChild(doc.createTextNode(3));
         trackElement.appendChild(任务id);

         元件TotalTime = doc.createElement(TotalTime);
         TotalTime.appendChild(doc.createTextNode(1));
         trackElement.appendChild(TotalTime);

         元件TrackDesc = doc.createElement(TrackDesc);
         TrackDesc.appendChild(doc.createTextNode(检测报));
         trackElement.appendChild(TrackDesc);

         元件的TrackID = doc.createElement(的TrackID);
         TrackId.appendChild(doc.createTextNode(0));
         trackElement.appendChild(的TrackID);

         的TransformerFactory TRANSFAC = TransformerFactory.newInstance();
         变压器反式=无效;
        尝试 {
            反式= transfac.newTransformer();
        }赶上(TransformerConfigurationException E){
            // TODO自动生成的catch块
            e.printStackTrace();
        }
         trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,是);
         trans.setOutputProperty(OutputKeys.INDENT,是);

         //创建XML树字符串
         StringWriter的SW =新的StringWriter();
         StreamResult结果=新StreamResult(SW);
         DOMSource的源=新DOMSource的(文件);
         尝试 {
            trans.transform(源,结果);
        }赶上(TransformerException中五){
            // TODO自动生成的catch块
            e.printStackTrace();
        }
         串的xmlString = sw.toString();
 

//发布XML文件到服务器

  DefaultHttpClient的HttpClient =新DefaultHttpClient();

         HttpPost httppost =新HttpPost(http://192.168.0.19:3334/cogglrestservice.svc/InsertTrack);
         //确保服务器知道什么样的回应,我们将接受
         httppost.addHeader(接受,为text / xml);
         //此外,一定要告诉什么样的内容,我们发送服务器
         httppost.addHeader(内容类型,应用程序/ XML);

         尝试
         {
         StringEntity实体=新StringEntity(的xmlString,UTF-8);
         entity.setContentType(应用程序/ XML);
         httppost.setEntity(实体);

         //执行是一个阻塞调用,最好把这种code在一个线程从用户界面的分离
         HTT presponse响应= httpClient.execute(httppost);

         BasicResponseHandler ResponseHandler的=新BasicResponseHandler();
            字符串strResponse = NULL;
            如果(响应!= NULL){
                尝试 {
                    strResponse = responseHandler.handleResponse(响应);
                }赶上(Htt的presponseException E){
                    e.printStackTrace();
                }赶上(IOException异常E){
                    e.printStackTrace();
                }
            }
            Log.e(WCF​​TEST,WCFTEST **********响应+ strResponse);


         }
         赶上(例外前)
         {
         ex.printStackTrace();
         }
         Toast.makeText(EditTask.thisXML成功地贴,Toast.LENGTH_SHORT).show();
 

I am using the below code to execute a HTTP POST request. The PostData is in the form of a String

Sample of PostData:

urn:marlin:broadband:1-1:registration-service:linkAcquisitionurn:marlin:organization:testpdc:device-maker-x:clientnemo:aa08a1:59ea7e8cfa7a8582http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" URI="urn:marlin:core:1.0:nemo:protocol:profile:1" wsu:Id="sigid0003" nemosec:Usage="http://nemo.intertrust.com/2005/10/security/profile"/></SOAP-ENV:Envelope>

We are expecting a xml/soap response, instead we are getting an xml file as the response. Can anyone tell me if the procedure to do an HTTP POST is correct (as in the below code)

Note: The same postData when used with cuRL for performing a POST is working fine.

public byte [] sendRecv(String PostData, long postDataSize){

  try{
   if(!(PostData.equals("empty"))){
    isPost = true;
    //InputStream postDataInputStream = new ByteArrayInputStream(postData);
    //BasicHttpEntity httpPostEntity = new BasicHttpEntity();
    //httpPostEntity.setContent(postDataInputStream);
    StringEntity httpPostEntity = new StringEntity(PostData, HTTP.UTF_8);
    //httpPostEntity.setContentLength(postData.length);
    //httpPostEntity.setContentType("application/x-www-form-urlencoded");
    httpPost.setEntity(httpPostEntity);
    httpPost.setHeader("Content-Length", new Integer(PostData.length()).toString());
    httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
    httpPost.setHeader("Expect", "100-continue");

   }
  }catch(Exception e) {
   e.printStackTrace();
  }

  try {
   if(isPost == true){
    response = mAndroidHttpClient.execute(httpPost);
    isPost = false;
   }
   else {
    response = mAndroidHttpClient.execute(httpGet);
   }
   statusCode = response.getStatusLine().getStatusCode();

   if(statusCode != 200 ){
    if(statusCode == 404) {
     //System.out.println("error in http connection : 404");

     //return ERR_HTTP_NOTFOUND
    } else if(statusCode == 500){
     //System.out.println("error in http connection : 500");
     //return ERR_HTTP_INTERNALSEVERERROR
    } else {
     //System.out.println("error in http connection : error unknown");
     //return ERR_HTTP_FATAL
    }
   }

   HttpEntity entity = response.getEntity();
   InputStream is = entity.getContent();

   ByteArrayOutputStream bos = new ByteArrayOutputStream();
   for (int next = is.read(); next != ENDOFSTREAM; next = is.read()) {
    bos.write(next);
   }
   responseBuffer = bos.toByteArray();
   bos.flush();
   bos.close();

   }catch (IOException e) {
    e.printStackTrace();
    }

   return responseBuffer;
 }
解决方案

//Creating xml file

          DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
         dbfac.setNamespaceAware(true);
         DocumentBuilder docBuilder = null;
         try {
            docBuilder = dbfac.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
         DOMImplementation domImpl = docBuilder.getDOMImplementation();
         Document doc = domImpl.createDocument("http://coggl.com/InsertTrack","TrackEntry", null);
         doc.setXmlVersion("1.0");
         doc.setXmlStandalone(true);

         Element trackElement = doc.getDocumentElement();

         Element CompanyId = doc.createElement("CompanyId");
         CompanyId.appendChild(doc.createTextNode("1"));
         trackElement.appendChild(CompanyId);

         Element CreatedBy = doc.createElement("CreatedBy");
         CreatedBy.appendChild(doc.createTextNode("6"));
         trackElement.appendChild(CreatedBy);

         Element DepartmentId = doc.createElement("DepartmentId");
         DepartmentId.appendChild(doc.createTextNode("4"));
         trackElement.appendChild(DepartmentId);

         Element IsBillable = doc.createElement("IsBillable");
         IsBillable.appendChild(doc.createTextNode("1"));
         trackElement.appendChild(IsBillable);

         Element ProjectId = doc.createElement("ProjectId");
         ProjectId.appendChild(doc.createTextNode("1"));
         trackElement.appendChild(ProjectId);

         Element StartTime = doc.createElement("StartTime");
         StartTime.appendChild(doc.createTextNode("2012-03-14 10:44:45"));
         trackElement.appendChild(StartTime);

         Element StopTime = doc.createElement("StopTime");
         StopTime.appendChild(doc.createTextNode("2012-03-14 11:44:45"));
         trackElement.appendChild(StopTime);

         Element TaskId = doc.createElement("TaskId");
         TaskId.appendChild(doc.createTextNode("3"));
         trackElement.appendChild(TaskId);

         Element TotalTime = doc.createElement("TotalTime");
         TotalTime.appendChild(doc.createTextNode("1"));
         trackElement.appendChild(TotalTime);

         Element TrackDesc = doc.createElement("TrackDesc");
         TrackDesc.appendChild(doc.createTextNode("dello testing"));
         trackElement.appendChild(TrackDesc);

         Element TrackId = doc.createElement("TrackId");
         TrackId.appendChild(doc.createTextNode("0"));
         trackElement.appendChild(TrackId);

         TransformerFactory transfac = TransformerFactory.newInstance();
         Transformer trans = null;
        try {
            trans = transfac.newTransformer();
        } catch (TransformerConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
         trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
         trans.setOutputProperty(OutputKeys.INDENT, "yes");

         //create string from xml tree
         StringWriter sw = new StringWriter();
         StreamResult result = new StreamResult(sw);
         DOMSource source = new DOMSource(doc);
         try {
            trans.transform(source, result);
        } catch (TransformerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
         String xmlString = sw.toString();

//posting xml file to server

         DefaultHttpClient httpClient = new DefaultHttpClient();

         HttpPost httppost = new HttpPost("http://192.168.0.19:3334/cogglrestservice.svc/InsertTrack");
         // Make sure the server knows what kind of a response we will accept
         httppost.addHeader("Accept", "text/xml");
         // Also be sure to tell the server what kind of content we are sending
         httppost.addHeader("Content-Type", "application/xml");

         try
         {
         StringEntity entity = new StringEntity(xmlString, "UTF-8");
         entity.setContentType("application/xml");
         httppost.setEntity(entity);

         // execute is a blocking call, it's best to call this code in a thread separate from the ui's
         HttpResponse response = httpClient.execute(httppost);

         BasicResponseHandler responseHandler = new BasicResponseHandler();
            String strResponse = null;
            if (response != null) {
                try {
                    strResponse = responseHandler.handleResponse(response);
                } catch (HttpResponseException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            Log.e("WCFTEST", "WCFTEST ********** Response" + strResponse);


         }
         catch (Exception ex)
         {
         ex.printStackTrace();
         }
         Toast.makeText(EditTask.this, "Xml posted succesfully.",Toast.LENGTH_SHORT).show();

这篇关于与Android HTTP POST问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 18:00