2

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. I want to create an xml and then I want to post that to the service and get a response from the service.

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:

 [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 :

   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.

enter image description here

How can I make post an xml file to this service from android. Any suggestions would be really appreciated.

G droid
  • 956
  • 5
  • 13
  • 36
  • I would like to know the reason for downvoting?? – G droid Sep 28 '15 at 10:55
  • why are you appending myXML with url, you should set xml as post request body – QAMAR Sep 28 '15 at 10:56
  • because when I try to pass it other way like httppost.setentity method ..it keeps telling me 404 error service not found – G droid Sep 28 '15 at 10:57
  • that is issue with your server side, not the client... However you should never send xml in url, If you have to send something to server in url then it should be URLEncoded – QAMAR Sep 28 '15 at 11:00
  • Convert xml to String and send like this with encoding-http://stackoverflow.com/questions/32591295/subsequent-https-post-request-in-java-with-cookies-retained/32592521#32592521 (replace https with http for unsecured server. – Ravindra babu Sep 28 '15 at 12:59

2 Answers2

0

To connect to WCF service on android you have to use external library like 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.

Adam Miśtal
  • 715
  • 4
  • 15
0
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();
    }

}

}
Nooruddin Lakhani
  • 7,507
  • 2
  • 19
  • 39