无法将 XML 字符串发布到 HTTP Android HttpPost 和 HttpUrlConnection

Trouble posting XML string to HTTP Android HttpPost and HttpUrlConnection

我对 Android 有点陌生,一直在努力处理 XML 字符串的 HTTP Post。我使用 HttpsUrlConnection 和 HttpPost 尝试了大约 5 个版本的代码,我 运行 遇到的问题是我的 XML 字符串没有进入我服务器上的应用程序,但是请求XML 正在进入 Apache 服务器。 我想要完成的是将 XML 中的用户名和 Pin 发送到我服务器上的 apache perl cgi XML。我已经使用 GET 完成了它并且效果很好但似乎无法让 POST 工作。 任何关于我可能做错了什么的见解,特别是如果我的代码看起来可以实现我的目标,那将是非常重要的 appreciated.Again 如果这是一个非常新的问题,我深表歉意。 谢谢你们:)

来自主activity的XML字符串是一个普通的XML,我在发送到函数之前添加了xmlsrc=。

String xml = "<?xml version=\"1.0\"encoding=\"UTF-8\"?><UserRequesting><NewUser>joseph</NewUser><Password>123456789</Password></UserRequesting>";

第一个片段是我最近使用 HttpsUrlConnection 的片段:

public void fetchLoginXML(){
    Log.d(TAG, "IN fetch ");
    HttpsURLConnection urlc;
    OutputStreamWriter out = null;
    DataOutputStream dataout;
    BufferedReader in = null;

    try {
        URL url = new URL(urlValuser);
        Log.d(TAG, "Final URL: " + url);
        urlc = (HttpsURLConnection) url.openConnection();
        urlc.setHostnameVerifier(new AllowAllHostnameVerifier());
        urlc.setRequestMethod("POST");

        urlc.setDoOutput(true);
        urlc.setDoInput(true);
        urlc.setUseCaches(false);
        urlc.setAllowUserInteraction(false);
        urlc.setRequestProperty("Content-Type", "text/xml");
        // perform POST operation
        Log.d(TAG, "Xml Source to POST: " + xmlsrc);
        String body = xmlsrc;
        OutputStream output = new BufferedOutputStream(urlc.getOutputStream());
        output.write(body.getBytes());
        output.flush();
        int responseCode = urlc.getResponseCode();
        in = new BufferedReader(new InputStreamReader(urlc.getInputStream()),8096);

        String response = "";

        String line = in.readLine();
        while (line != null) {
            response += line;
            line = in.readLine();
        }

        Log.d(TAG, "Post results Response Code " + responseCode);
        Log.d(TAG, "Post results Response " + response);

        in.close();

        factory = XmlPullParserFactory.newInstance();
        XmlPullParser myparser = factory.newPullParser();
        Log.d(TAG, "Setting myparser paramaters ");
        myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
        Log.d(TAG, "Setting myparser input into xmldata ");
        myparser.setInput(new StringReader(response));
        Log.d(TAG, "send myparser to function parsexmlandstoreit ");
        parseXMLAndStoreIt(myparser);

    } catch (Exception e) {
        Log.e(TAG, "Error Posting Data: " + e.toString());
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

我的第二个版本使用的是 HttpPost:

public void postData(String sendData) throws Exception {
    // Create a new HttpClient and Post Header
    Log.d(TAG, "Sending Data: " + sendData);
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("https://joes....");
    httppost.addHeader("Accept", "text/xml");

    try {
        StringEntity se = new StringEntity(sendData);
        se.setContentType("text/xml");
        httppost.setEntity(se);
        // Execute HTTP Post Request
        Log.d(TAG, "Execute HTTP POST");
        HttpResponse response = httpclient.execute(httppost);
        Log.d(TAG, "Message Sent :)");
        InputStream ips  = response.getEntity().getContent();
        BufferedReader buf = new BufferedReader(new InputStreamReader(ips,"UTF-8"));

        if(response.getStatusLine().getStatusCode()!= HttpStatus.SC_OK)
        {
            Log.e(TAG, "Response: " + response.getStatusLine().getReasonPhrase());
            throw new Exception(response.getStatusLine().getReasonPhrase());
        }

        Log.d(TAG, "Response: " + response.getStatusLine().getReasonPhrase());
        String received = "";

        String line = buf.readLine();
        while (line != null) {
            received += line;
            line = buf.readLine();
        }

        StringBuilder sb = new StringBuilder();
        String s;
        while(true)
        {
            s = buf.readLine();
            if(s==null || s.length()==0)
                break;
            sb.append(s);

        }
        buf.close();
        ips.close();
        sb.toString();

        factory = XmlPullParserFactory.newInstance();
        XmlPullParser myparser = factory.newPullParser();
        Log.d(TAG, "Setting myparser paramaters ");
        myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
        Log.d(TAG, "Setting myparser input into xmldata ");
        myparser.setInput(new StringReader(received));
        Log.d(TAG, "send myparser to function parsexmlandstoreit ");
        parseXMLAndStoreIt(myparser);
    }
    catch (ClientProtocolException e)
    {
        Log.d(TAG, "Client Protocol Error: " + e);
        e.printStackTrace();
        // TODO Auto-generated catch block
    }
    catch (IOException e)
    {
        Log.d(TAG, "I/O Error: " + e);
        e.printStackTrace();
        // TODO Auto-generated catch block
    }
}

所以在很长一段时间试图理解为什么这会攻击 apache 服务器而不是我们在服务器上的应用程序之后,我发现我需要在 POST 之前创建一个缓冲体,然后将缓冲流写入服务器。

像这样:

  URL url = new URL(urlValuser);
        Log.d(TAG, "URL to POST to: " + url);
        HttpsURLConnection urlc = (HttpsURLConnection) url.openConnection();
        urlc.setReadTimeout(10000);
        urlc.setConnectTimeout(15000);
        urlc.setRequestMethod("POST");
        urlc.setDoInput(true);
        urlc.setDoOutput(true);
        // perform POST operation
        OutputStream os = urlc.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        writer.write(xmlToPost);
        writer.flush();
        writer.close();
        os.close();

        int responseCode = urlc.getResponseCode();
        in = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
        String response = "";
        String line = in.readLine();
        while (line != null) {
            System.out.println(response);
            response += line;
            line = in.readLine();
        }
        Log.d(TAG, "Post results Response Code " + responseCode);
        Log.d(TAG, "Post results Response " + response);

        in.close();

        return response;
        writer.write(xmlToPost);
        writer.flush();
        writer.close();
        os.close();