简体   繁体   中英

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 . 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.

在此处输入图片说明

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

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.

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

}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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