Как передать значение параметра, используя HttpPost и NameValuePair в Android при доступе к остальной веб-службы? - PullRequest
3 голосов
/ 23 августа 2011

Я сделал остальную веб-службу с контрактом на обслуживание, как показано ниже

[OperationContract]
[WebInvoke(Method = "POST",
            ResponseFormat = WebMessageFormat.Xml,
            BodyStyle = WebMessageBodyStyle.Wrapped,
            UriTemplate = "postdataa?id={id}"
            )]
string PostData(string id);

Реализация метода PostData

public string PostData(string id)
        {
            return "You posted " + id;
        }

Код в Android для публикации данных в веб-сервисе

HttpClient httpclient = new DefaultHttpClient();
        HttpHost target = new HttpHost("192.168.1.4",4567);
        HttpPost httppost = new HttpPost("/RestService.svc/postdataa?");

        String result=null;
        HttpEntity entity = null;

        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
            nameValuePairs.add(new BasicNameValuePair("id", "1"));
            UrlEncodedFormEntity ent = new UrlEncodedFormEntity(nameValuePairs);
            httppost.setEntity(ent);

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(target, httppost);
            entity = response.getEntity();
            //get xml result in string
            result = EntityUtils.toString(entity);

} catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }

Проблема в том, что отображается результат xml, а значение параметра отсутствует :

<PostDataResponse xmlns="http://tempuri.org/"><PostDataResult>You posted </PostDataResult></PostDataResponse>

Я не знаю, что пошло не так.

1 Ответ

0 голосов
/ 23 августа 2011

Поскольку вы используете службу REST, попробуйте:

private static char[] GetData(String servicePath) throws Exception
{           
     InputStream stream = null;     
     String serviceURI = SERVICE_URI;//this is your URI to the service
     char[] buffer = null;
     try        
     {
        if (servicePath != "")
           serviceURI = serviceURI + servicePath; 
        DefaultHttpClient httpClient = new DefaultHttpClient();

        HttpGet request = new HttpGet(serviceURI);

        request.setHeader("Accept", "application/xml");
        request.setHeader("Content-type", "application/xml");

        HttpResponse response = httpClient.execute(request);

        HttpEntity responseEntity = response.getEntity();    
        if (responseEntity != null)
        {
            // Read response data into buffer
            buffer = new char[(int)responseEntity.getContentLength()];
            stream = responseEntity.getContent();
            InputStreamReader reader = new InputStreamReader(stream);
            reader.read(buffer);
            stream.close();  
        }
    }
    catch (Exception e)
    {
        Log.i("Survey Application", e.getMessage());
        throw e;
    }       
    return buffer;
}

Вызовите этот метод, используя

try
{
     char[] buffer = GetData("postdataa/" + id);
     if (buffer != null)
          //Build your XML object
}
catch (Exception e)
{

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...