简体   繁体   English

如何在Android中发出httppost请求?

[英]How can I make an httppost request in Android?

I know this should have been easy to find online but none of the articles addressed my issue so I am coming to SO for some help.I am trying to make an httppost request in android to a wcf restful web service . 我知道这应该很容易在网上找到,但是没有一篇文章解决了我的问题,因此我来寻求帮助。我试图在android中向wcf宁静的Web服务发出一个httppost 请求 I want to create an xml and then I want to post that to the service and get a response from the service. 我想创建一个xml ,然后将其发布到服务并从服务获得响应。

I have created a WCF Rest service and it has a method to accept the xml and respond back.Here is the code for the method: 我创建了一个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);
        }

Here is android code to post xml : 这是发布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); 

This code crasehes throwing an illegal character in the path exception. 此代码禁止在路径异常中抛出非法字符。

在此处输入图片说明

How can I make post an xml file to this service from android. 我该如何从android将xml文件发布到此服务。 Any suggestions would be really appreciated. 任何建议将不胜感激。

To connect to WCF service on android you have to use external library like ksoap. 要在Android上连接到WCF服务,您必须使用外部库(如ksoap)。 enter link description here 在此处输入链接说明

Then you can adapt for your needs this class: 然后,您可以在本课程中适应您的需求:

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


}

Use this class like: 像这样使用此类:

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

Use this asynck task only in application context.Pass data to Activity / fragment only using EventBus from green roboot or otto. 仅在应用程序上下文中使用此异步任务。仅使用绿色roboot或otto中的EventBus将数据传递到Activity / fragment。

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

}

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM