如何发布XML数据在安卓服务器 [英] how to post xml data to server in android

查看:138
本文介绍了如何发布XML数据在安卓服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于我是新到Android请为我提供的教程的链接来发布XML数据的服务器上。我面临的问题是执行职务的请求

 公共无效uploadFileToServer()
 {
      DefaultHttpClient的HttpClient =新DefaultHttpClient();
      HttpPost httppost =新HttpPost(url_context +/命令/命令);
      httppost.addHeader(接受,为text / xml);
      httppost.addHeader(内容类型,应用程序/ XML);
      尝试
      {
          StringEntity实体=新StringEntity(的xmlString,UTF-8);
          entity.setContentType(应用程序/ XML);
          httppost.setEntity(实体);
          HTT presponse响应= httpClient.execute(httppost);
          BasicResponseHandler ResponseHandler的=新BasicResponseHandler();
             字符串strResponse = NULL;
             如果(响应!= NULL)
             {
                 尝试 {
                     strResponse = responseHandler.handleResponse(响应);
                    }赶上(Htt的presponseException E)
                    {
                        e.printStackTrace();
                    }赶上(IOException异常E)
                    {
                            e.printStackTrace();
                    }
             }

      }
      赶上(例外前)
      {
                 ex.printStackTrace();
      }
 }
 

解决方案

craete基于此示例XML文件

 的DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder的docBuilder = docFactory.newDocumentBuilder();

    //根元素
    文档的文档= docBuilder.newDocument();
    元rootElement的= doc.createElement(订单);
    doc.appendChild(rootElement的);

    //设置属性类
    ATTR RATTR = doc.createAttribute(Order_atrribute);
    Rattr.setValue(curtrade);
    rootElement.setAttributeNode(RATTR);

        // companyid元素
        元的员工= doc.createElement(companyid);
        rootElement.appendChild(工作人员);
        //缩短方式
        // staff.setAttribute(ID,1);

        //名字元素
        元素名字= doc.createElement(的OrderItems);
        firstname.appendChild(doc.createTextNode(HII));
        staff.appendChild(名字);
 

和写的内容转换成XML文件

 的TransformerFactory的TransformerFactory = TransformerFactory.newInstance();
    变压器变压器= transformerFactory.newTransformer();
    DOMSource的源=新DOMSource的(文件);
    StreamResult结果=新StreamResult(新文件(this.getFilesDir()getAbsolutePath(),file.xml));
    //的String = this.getFilesDir()getAbsolutePath();
    //输出到控制台进行测试
    // StreamResult结果=新StreamResult(的System.out);
    transformer.transform(源,结果);
 

上传您的文件

  DefaultHttpClient的HttpClient =新DefaultHttpClient();
    HttpPost httppost =新HttpPost(url_context +/orders/order.php);
    字符串文件路径= this.getFilesDir()getAbsolutePath()。
    文件F =新的文件(文件路径,file.xml);
    // byte []的数据= FileOperator.readBytesFromFile(F);
    字符串的内容= getFileContents(F);
    StringEntity SE =新StringEntity(内容,HTTP.UTF_8);
    se.setContentType(为text / xml);
    httppost.setEntity(SE);
    f.delete();
    HTT presponse HTT presponse = httpClient.execute(httppost);
    Log.d(xml1,HTT presponse.toString());
    HttpEntity resEntity = HTT presponse.getEntity();
    Log.d(XML2,resEntity.toString());
    字符串RESULT1 = EntityUtils.toString(resEntity);
    Log.d(XML,作家=+ RESULT1);
 

梅索德ge​​tFileContent是

 公共字符串getFileContent(最后文件的文件)抛出IOException异常{
    最后的InputStream的InputStream =新的FileInputStream(文件);
    最后的BufferedReader读卡器=新的BufferedReader(新的InputStreamReader(InputStream中));
    最后StringBuilder的StringBuilder的=新的StringBuilder();

    布尔做= FALSE;
    而(!做){
        最后串线= reader.readLine();
        做=(行== NULL);

        如果(线!= NULL){
            stringBuilder.append(线);
        }
    }
    reader.close();
    inputStream.close();

    返回stringBuilder.toString();
}
 

<一个href="http://xjaphx.word$p$pss.com/2011/10/27/android-xml-adventure-create-write-xml-data/">reference

As i am new to android Please provide me the link of the tutorial to post xml data on the server. I am facing the problem is executing the post request

public void uploadFileToServer()
 {
      DefaultHttpClient httpClient = new DefaultHttpClient();
      HttpPost httppost = new HttpPost(url_context + "/orders/order"); 
      httppost.addHeader("Accept", "text/xml");
      httppost.addHeader("Content-Type", "application/xml");
      try
      {
          StringEntity entity = new StringEntity(xmlString, "UTF-8");
          entity.setContentType("application/xml");
          httppost.setEntity(entity);
          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();
                    }
             }

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

解决方案

craete your xml file based on this example

DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

    // root elements
    Document doc = docBuilder.newDocument();
    Element rootElement = doc.createElement("Order");
    doc.appendChild(rootElement);

    //set attribute to class
    Attr Rattr = doc.createAttribute("Order_atrribute");
    Rattr.setValue(curtrade);
    rootElement.setAttributeNode(Rattr);

        // companyid elements
        Element staff = doc.createElement("companyid");
        rootElement.appendChild(staff);
        // shorten way
        // staff.setAttribute("id", "1");

        // firstname elements
        Element firstname = doc.createElement("orderitems");
        firstname.appendChild(doc.createTextNode("hii"));
        staff.appendChild(firstname);

and write the content into xml file

TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(new File(this.getFilesDir().getAbsolutePath(),"file.xml"));
    //String s=this.getFilesDir().getAbsolutePath();
    // Output to console for testing
    //StreamResult result = new StreamResult(System.out);
    transformer.transform(source, result);

post your file by

DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url_context + "/orders/order.php");
    String filePath = this.getFilesDir().getAbsolutePath();
    File f=new File(filePath,"file.xml");
    //byte[] data = FileOperator.readBytesFromFile(f);
    String content=getFileContents(f);
    StringEntity se = new StringEntity( content, HTTP.UTF_8);
    se.setContentType("text/xml");
    httppost.setEntity(se);
    f.delete();
    HttpResponse httpresponse = httpClient.execute(httppost);
    Log.d("xml1", httpresponse.toString());
    HttpEntity resEntity = httpresponse.getEntity();
    Log.d("xml2", resEntity.toString());
    String result1 = EntityUtils.toString(resEntity);
    Log.d("xml", "writer = "+result1);

methode getFileContent is

public String getFileContent(final File file) throws IOException {
    final InputStream inputStream = new FileInputStream(file);
    final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    final StringBuilder stringBuilder = new StringBuilder();

    boolean done = false;  
    while (!done) {
        final String line = reader.readLine();
        done = (line == null);

        if (line != null) {
            stringBuilder.append(line);
        }
    }
    reader.close();
    inputStream.close();

    return stringBuilder.toString();
}

reference

这篇关于如何发布XML数据在安卓服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆