与Android HTTP POST问题问题、Android、HTTP、POST

2023-09-05 05:15:28 作者:宅男乖不乖

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

中的PostData样品:

金塔:枪鱼:广 频段:1-1:registr 通货膨胀业务:丽 nkAcquisitionurn: 马林:organizat 离子:testpdc:德维 CE制造商-X:CLIEN tnemo:aa08a1:59E a7e8cfa7a8582http://docs.oasi s-open.org/wss/2 004/01 /绿洲-200 401-WSS-wssecuri TY-公用事业1.0.x的 SDURI =金塔:三月 林:核心:1.0:NEM ○:协议:PROFI 乐:1华盛顿州立大学:ID =SI gid0003nemosec :用法=HTTP://ñ emo.intertrust.c OM / 2005/10 / SECUR 性/配置文件/>< / SOAP-ENV:Envelo PE>

我们期待一个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();
 
Android HTTPPOST请求报错

//发布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:broad band:1-1:registr ation-service:li nkAcquisitionurn: marlin:organizat ion:testpdc:devi ce-maker-x:clien tnemo:aa08a1:59e a7e8cfa7a8582http://docs.oasi s-open.org/wss/2 004/01/oasis-200 401-wss-wssecuri ty-utility-1.0.x sd" URI="urn:mar lin:core:1.0:nem o:protocol:profi le:1" wsu:Id="si gid0003" nemosec :Usage="http://n emo.intertrust.c om/2005/10/secur ity/profile"/>< /SOAP-ENV:Envelo pe>

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();