簡體   English   中英

Android HttpsURLConnection post問題

[英]Android HttpsURLConnection post problem

我的 android 應用程序中有以下活動,該應用程序創建帶有身份驗證的 httpsurlconnection。 然后它會發布一些 XML 並捕獲響應。 我從服務器收到的響應是沒有收到 XML 消息,但日志中沒有異常。

我已經測試了與 Java 應用程序相同的代碼,它工作正常。 我已經搜索了幾個星期,但似乎找不到答案。

我在清單文件中設置了 android.permission.INTERNET。

任何幫助將不勝感激,我在下面發布了我的代碼,減去了連接中使用的用戶名和密碼。

活動:

package com.payments.WorldPay;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class OrderModification extends Activity
{   
  TextView resultMessage;

  @Override
  public void onCreate(Bundle savedInstanceState)   
  {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.order_modification);

    Button submit = (Button)findViewById(R.id.submitButton);
    submit.setOnClickListener(submitModification);
    resultMessage = (TextView)this.findViewById(R.id.result);
  }

  OnClickListener submitModification = new OnClickListener()
    {
      public void onClick(View v) 
      {             
        StringBuffer xmlMod = new StringBuffer();

        xmlMod.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        xmlMod.append("<!DOCTYPE paymentService PUBLIC \"-//RBS WorldPay/DTD RBS WorldPay 
        PaymentService v1//EN\" \"http://dtd.wp3.rbsworldpay.com/paymentService_v1.dtd\">");
        xmlMod.append("<paymentService version=\"1.4\" merchantCode=\"TECHSUPPORT\">");
        xmlMod.append("<modify>");
        xmlMod.append("<orderModification orderCode=\"123456789\">");
        xmlMod.append("<cancel/>");
        xmlMod.append("</orderModification>");
        xmlMod.append("</modify>");
        xmlMod.append("</paymentService>");

        SendXml sendMod = new SendXml(xmlMod.toString());
        resultMessage.setText(sendMod.submitOrder());
      }
    };
}

連接 Class:

package com.payments.WorldPay;

import java.io.*;
import java.net.*;
import javax.net.ssl.HttpsURLConnection;

public class SendXml
{    
  protected final static String merchantCode="username";    
  protected final static String xmlPassword="password";
  protected final static String envUrl="https://secure-test.wp3.rbsworldpay.com/jsp/merchant/xml/paymentService.jsp";    
  protected String xmlRequest;

  public SendXml(String xmlRequest)
  {       
    this.xmlRequest = xmlRequest;    
  }        

  public String submitOrder()    
  {     
    HttpsURLConnection conn = null;         

    try     
    {                       
      System.setProperty("http.keepAlive", "false");                                    

      Authenticator.setDefault(new MyAuthenticator());            
      URL url = new URL(envUrl);

      conn = (HttpsURLConnection)url.openConnection();                        
      conn.setRequestMethod("POST");            
      conn.setRequestProperty("Content-Type", "text/xml");            
      conn.setDoInput(true);            
      conn.setDoOutput(true);            
      conn.setUseCaches(false);            
      conn.setAllowUserInteraction(false);            
      conn.setConnectTimeout(30000);

      String utf8Xml = URLEncoder.encode(xmlRequest, "UTF-8");
      DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
      wr.writeBytes(utf8Xml);
      wr.flush();
      wr.close();

      InputStream response;

      if(conn.getResponseCode()==200)
      { 
        response = conn.getInputStream();
      }
      else
      { 
        response = conn.getErrorStream();
      }

      BufferedReader in = new BufferedReader(new InputStreamReader(response),4800); 
      StringBuffer responseBuffer = new StringBuffer();
      String line;

      while ((line = in.readLine()) != null) 
      { 
        responseBuffer.append(line);
      }

      in.close();

      return responseBuffer.toString();     
    }   
    catch(Exception e)
    {   
      return("Connection Error: "+e);
    }
    finally 
    {
      conn.disconnect(); 
    }
  }

  public static class MyAuthenticator extends Authenticator
  {
    public PasswordAuthentication getPasswordAuthentication()
    {
      return (new PasswordAuthentication(merchantCode, xmlPassword.toCharArray()));
    }
  }
}

我再次將代碼作為 Java 項目運行,它工作正常。 我在下面包含了示例請求和響應。

要求:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE paymentService PUBLIC "-//RBS WorldPay/DTD RBS WorldPay PaymentService v1//EN"         
"http://dtd.wp3.rbsworldpay.com/paymentService_v1.dtd">
<paymentService version="1.4" merchantCode="TECHSUPPORT">
  <modify>
    <orderModification orderCode="123456789">
      <cancel/>
    </orderModification>
  </modify>
</paymentService>

回復:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE paymentService PUBLIC "-//Bibit//DTD Bibit PaymentService v1//EN" 
"http://dtd.bibit.com/paymentService_v1.dtd">
<paymentService version="1.4" merchantCode="TECHSUPPORT">
  <reply>
    <ok>
      <cancelReceived orderCode="123456789"/>
    </ok>
  </reply>
</paymentService>

如果我只是從上面的元素中刪除 >,我將收到下面的錯誤。

錯誤響應:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE paymentService PUBLIC "-//Bibit//DTD Bibit PaymentService v1//EN" 
"http://dtd.bibit.com/paymentService_v1.dtd">
<paymentService version="1.4" merchantCode="TECHSUPPORT">
  <reply>
    <error code="2">
      <![CDATA[Element type "modify" must be followed by either attribute specifications, ">" or 
      "/>".]]>
    </error>
  </reply>
</paymentService>

在此先感謝達倫

我沒有找到問題的答案,但下面的代碼允許我成功發布我的 XML。

public ArrayList<PaymentResult> submitOrder()
{
    HttpClient client = new DefaultHttpClient();
    HttpPost request = new HttpPost(envUrl);
    UsernamePasswordCredentials login = new UsernamePasswordCredentials(merchantCode, xmlPassword);
    StringBuffer responseBuffer = null;     

    try
    {                       
        request.addHeader(BasicScheme.authenticate(login,"UTF-8",false)); 

        StringEntity xmlmessage = new StringEntity(xmlRequest,HTTP.UTF_8);
        xmlmessage.setContentType("text/xml");  
        request.setHeader("Content-Type","text/xml;charset=UTF-8");
        request.setEntity(xmlmessage); 

        HttpResponse response = client.execute(request);   
        BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        responseBuffer = new StringBuffer();
        String line;

        while ((line = in.readLine()) != null)
        {
            responseBuffer.append(line);
        }
        in.close();
    }   
    catch(Exception e)
    {
        e.printStackTrace();
    }
    return parseResponse(responseBuffer.toString());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM