【问题标题】:How can I make an httppost request in Android?如何在 Android 中发出 httppost 请求?
【发布时间】:2015-09-28 10:52:18
【问题描述】:

我知道这应该很容易在网上找到,但没有一篇文章解决了我的问题,所以我来寻求帮助。我正在尝试在 android 中向 wcf restful web 服务发出 httppost 请求。我想创建一个 xml,然后我想将它发布到服务并获得服务的响应。

我创建了一个 WCF Rest 服务,它有一个接受 xml 并做出响应的方法。这是该方法的代码:

 [OperationContract]
            [WebInvoke(Method = "POST",
                   RequestFormat = WebMessageFormat.Xml,
                   ResponseFormat = WebMessageFormat.Xml,
                   UriTemplate = "DoWork1/{xml}",
                   BodyStyle = WebMessageBodyStyle.Wrapped)]
            XElement DoWork1(string xml);

     public XElement DoWork1(string xml)
            {
                StreamReader reader = null;
                XDocument xDocRequest = null;
                string strXmlRequest = string.Empty;
                reader = new StreamReader(xml);
                strXmlRequest = reader.ReadToEnd();
                xDocRequest = XDocument.Parse(strXmlRequest);
                string response = "<Result>OK</Result>";
                return XElement.Parse(response);
        }

这是发布 xml 的 android 代码:

   String myXML = "<? xml version=1.0> <Request> <Elemtnt> <data id=\"1\">E1203</data> <data id=\"2\">E1204</data> </Element> </Request>";
                HttpClient httpClient = new DefaultHttpClient();
                                        // replace with your url
                HttpPost httpPost = new HttpPost("http://192.168.0.15/Httppost/Service1.svc/DoWork1/"+myXML); 

此代码在路径异常中抛出非法字符。

如何将 xml 文件从 android 发布到此服务。任何建议将不胜感激。

【问题讨论】:

  • 我想知道投反对票的原因??
  • 为什么要在 myXML 后面加上 url,你应该将 xml 设置为 post request body
  • 因为当我尝试通过 httppost.setentity 方法等其他方式传递它时,它一直告诉我找不到 404 错误服务
  • 这是你的服务器端的问题,而不是客户端的问题......但是你不应该在 url 中发送 xml,如果你必须在 url 中向服务器发送一些东西,那么它应该是 URLEncoded
  • 将 xml 转换为字符串并使用 encoding-stackoverflow.com/questions/32591295/… 像这样发送(对于不安全的服务器,将 https 替换为 http。

标签: java c# android xml wcf


【解决方案1】:
public class HTTPPostActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    makePostRequest();

}
private void makePostRequest() {


    HttpClient httpClient = new DefaultHttpClient();
                            // replace with your url
    HttpPost httpPost = new HttpPost("www.example.com"); 


    //Post Data
    List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
    nameValuePair.add(new BasicNameValuePair("username", "test_user"));
    nameValuePair.add(new BasicNameValuePair("password", "123456789"));


    //Encoding POST data
    try {
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
    } catch (UnsupportedEncodingException e) {
        // log exception
        e.printStackTrace();
    }

    //making POST request.
    try {
        HttpResponse response = httpClient.execute(httpPost);
        // write response to log
        Log.d("Http Post Response:", response.toString());
    } catch (ClientProtocolException e) {
        // Log exception
        e.printStackTrace();
    } catch (IOException e) {
        // Log exception
        e.printStackTrace();
    }

}

}

【讨论】:

    【解决方案2】:

    要连接到 Android 上的 WCF 服务,您必须使用外部库,如 ksoap。 enter link description here

    那么你可以适应这个类来满足你的需要:

    public abstract class SoapWorker extends AsyncTask<SoapWorker.SoapRequest,Void,Object> {
    
    public static class SoapRequest{
    
        private LinkedHashMap<String,Object> params;
        private String methodName;
        private String namespace;
        private String actionName;
        private String url;
        public SoapRequest(String url, String methodName,String namespace){
            this.methodName = methodName;
            this.params = new LinkedHashMap<>();
            this.namespace=namespace;
            this.actionName=this.namespace + "IService/" + methodName;
            this.url=url;
        }
        public void addParam(String key,Object value){
            this.params.put(key,value);
        }
    }
    
    @Override
    protected Object doInBackground(SoapRequest input) {
    
        try {
            SoapObject request = new SoapObject(input.namespace, input.methodName);
            for(Map.Entry<String, Object> entry : input.params.entrySet()){
                request.addProperty(entry.getKey(),entry.getValue());
            }
            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
            envelope.dotNet = true;
            envelope.setOutputSoapObject(request);
            HttpTransportSE androidHttpTransport = new HttpTransportSE(input.url);
            androidHttpTransport.call(input.actionName, envelope);
            input.params.clear();
    
            return parseResponse(envelope.getResponse());
        } catch (Exception e) {
            Log.e("SoapWorker", "error " + e);
            return e;
        }
    
    }
    
    @WorkerThread
    public abstract Object parseResponse(Object response);
    
    
    }
    

    像这样使用这个类:

     SoapWorker.SoapRequest request = new SoapWorker.SoapRequest(URL,METHOD_NAME,NAMESPACE);
        request.addParam(KEY,VALUE);
        ....
        request.addParam(KEY,VALUE);
    
        SoapWorker worker = new SoapWorker(){
    
            @Override
            public Object parseResponse(Object response) {
                if(response==null)
                    return null;
               //parse response
               // this is background thread
                return response;
            }
    
            @Override
            protected void onPostExecute(Object o) {
                super.onPostExecute(o);
               // this is ui thread
               //update your ui
            }
        };
        worker.execute(request);
    

    仅在应用程序上下文中使用此异步任务。仅使用来自绿色 roboot 或 otto 的 EventBus 将数据传递给 Activity / Fragment。

    【讨论】:

      猜你喜欢
      • 2014-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-05
      • 1970-01-01
      • 2012-06-28
      • 2020-12-25
      相关资源
      最近更新 更多