【问题标题】:How to make a webservice to request to C# based webservice in android?如何在android中创建一个webservice来请求基于C#的webservice?
【发布时间】:2016-05-18 16:57:12
【问题描述】:

我正在开发一个 web 服务调用模块,我有一个用 C# 构建的调用 web 服务的文档,我只用 JSON 调用了 web 服务,不知道如何向这样的 web 服务发出请求,任何朋友可以帮助我如何提出请求并从此类网络服务中获得响应,我的网络服务详细信息如下,

网络服务基础网址:http://www.fansplay.com/wsfpbtest/FBS.svc

API 名称:GetContestants

Request format:

{“ APIUserName”: “admin” , “Password”: “*****”}

Response:

{
    "Contestants": [
        {
            "Age": 19,
            "Bio": "",
            "City": "Agra",
            "ContestantID": 11,
            "CurrentWeekPoints": 0,
            "FirstName": "Merlin",
            "ImageURL": "http://localhost:41800/FansPlayBachelor/Player/11.jpg",
            "LastName": "M",
            "Occupation": "Student",
            "State": "Delhi",
            "Status": "A",
            "TotalPoints": 0
        },
        {
            "Age": 25,
            "Bio": "",
            "City": "chennai",
            "ContestantID": 12,
            "CurrentWeekPoints": 0,
            "FirstName": "James",
            "ImageURL": "http://localhost:41800/FansPlayBachelor/Player/12.jpg",
            "LastName": "S",
            "Occupation": "Marketing",
            "State": "tamilnadu",
            "Status": "A",
            "TotalPoints": 0
        }
        ],
    "ResponseCode": true,
    "ResponseMessage": "Success"
}

我试过如下:

private class AsyncCaller extends AsyncTask<Void, Void, Void>
    {
        ProgressDialog pdLoading = new ProgressDialog(StartActivity.this);

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            //this method will be running on UI thread
            pdLoading.setMessage("Loading...");
            pdLoading.show();
        }
        @Override
        protected Void doInBackground(Void... params) {

            //this method will be running on background thread so don't update UI frome here
            //do your long running http tasks here,you dont want to pass argument and u can access the parent class' variable url over here
             HttpClient httpclient = new DefaultHttpClient();

                // 2. make POST request to the given URL
                HttpPost httpPost = new HttpPost("http://www.fansplay.com/wsfpbtestV3/FBS.svc/GetContestants");

                String json = "";
     try{
                // 3. build jsonObject
                JSONObject jsonObject = new JSONObject();
                jsonObject.accumulate("APIUserName", "Rjfk@vDV43F");
                jsonObject.accumulate("Password", "79C8RE30-ELJD-4617-VX2D-A374C8C59E3F");

                // 4. convert JSONObject to JSON to String
                json = jsonObject.toString();
                String req =URLEncoder.encode(json, "utf-8");
                // ** Alternative way to convert Person object to JSON string usin Jackson Lib 
                // ObjectMapper mapper = new ObjectMapper();
                // json = mapper.writeValueAsString(person); 

                // 5. set json to StringEntity
                StringEntity se = new StringEntity(req);

                // 6. set httpPost Entity
                httpPost.setEntity(se);

                // 7. Set some headers to inform server about the type of the content   
                httpPost.setHeader("Accept", "application/json");
                httpPost.setHeader("Content-type", "application/json");

                // 8. Execute POST request to the given URL
                HttpResponse httpResponse = httpclient.execute(httpPost);

                // 9. receive response as inputStream
                inputStream = httpResponse.getEntity().getContent();

                // 10. convert inputstream to string
                if(inputStream != null)
                    result = convertInputStreamToString(inputStream);
                else
                    result = "Did not work!";}
     catch(Exception e){
         e.printStackTrace();
     }

            return null;
}

我不知道这是哪种网络服务,所以任何人都可以帮助我,因为我在这 4 天以来一直处于困境。

【问题讨论】:

    标签: c# android json web-services wsdl


    【解决方案1】:

    这是一个返回 XML 或 JSON 的 Web 服务。

    对于 XML:

    1. 您可以使用SoapUI 来测试和检查Web 服务。
    2. 您可以使用 ksoap2-androidIceSoap 等库将 SOAP 消息发送到 Web 服务,但我们将使用 java.net.HttpURLConnection

    对于 JSON:

    1. 您可以使用Postman 来测试和检查Web 服务。

    调用Web Service所需的步骤:

    1. 打开您的 AndroidManifest.xml 并添加互联网权限&lt;uses-permission android:name="android.permission.INTERNET"&gt;&lt;/uses-permission&gt;
    2. 编写调用 Web 服务上的 GetContestants 操作的代码。
    3. 编写代码来解析从 GetContestants 操作接收到的数据。
    4. 编写代码以使用调用和封装上述方法的 AsyncTask,这样就不会全部发生在主 UI 线程上。

    对于 XML,示例代码(步骤 2)在 Web 服务上调用基于 SOAP 的 GetContestants 操作:

    private String getContestants(String username, String password) throws Exception {
        URL obj = new URL("http://www.fansplay.com/wsfpbtest/FBS.svc/SOAP");
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-type", "text/xml; charset=utf-8");
        con.setRequestProperty("SOAPAction", "http://tempuri.org/IFBS/GetContestants");
    
        String reqXML = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\"http://tempuri.org/\" xmlns:fbs=\"http://schemas.datacontract.org/2004/07/FBService\">\n" +
                "   <soapenv:Header/>\n" +
                "   <soapenv:Body>\n" +
                "      <tem:GetContestants>\n" +
                "         <tem:objContestant>\n" +
                "            <fbs:APIUserName>" + username + "</fbs:APIUserName>\n" +
                "            <fbs:Password>" + password +"</fbs:Password>\n" +
                "         </tem:objContestant>\n" +
                "      </tem:GetContestants>\n" +
                "   </soapenv:Body>\n" +
                "</soapenv:Envelope>";
    
        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(reqXML);
        wr.flush();
        wr.close();
    
        // Read response
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
    
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
    
        return response.toString();
    }
    

    调用上述方法如下:String xml = getContestants("Rjfk@vDV43F", "79C8RE30-ELJD-4617-VX2D-A374C8C59E3F");

    对于 JSON,在 Web 服务上调用 GetContestants 方法的示例代码(步骤 2):

    private String getContestants(String username, String password) throws Exception {
        URL obj = new URL("http://www.fansplay.com/wsfpbtestV3/FBS.svc/GetContestants");
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-type", "text/json");
    
        String jsonBody = String.format("{\"APIUserName\": \"%s\" , \"Password\": \"%s\"}", username, password);
    
        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(jsonBody);
        wr.flush();
        wr.close();
    
        // Read response
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
    
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
    
        return response.toString();
    }
    

    调用上述方法如下:String json = getContestants("Rjfk@vDV43F", "79C8RE30-ELJD-4617-VX2D-A374C8C59E3F");

    对于 XML,解析和提取参赛者数据的示例代码(步骤 3):

    private void parseContestants(String xml) throws ParserConfigurationException, IOException, SAXException {
        // Build a Document from the XML
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = factory.newDocumentBuilder();
        InputSource inStream = new InputSource();
        inStream.setCharacterStream(new StringReader(xml));
        Document doc = db.parse(inStream);
    
        NodeList nl = doc.getElementsByTagName("a:Contestant");
        for(int i = 0; i < nl.getLength(); i++) {
            Node node = nl.item(i);
            if (node instanceof Element) {
                Node contestant = (Element) node;
                // Extract the contestant data
                NodeList contestantProperties = contestant.getChildNodes();
    
                if (contestantProperties.item(0).getFirstChild() != null) {
                    String age = contestantProperties.item(0).getFirstChild().getNodeValue();
                }
    
                if (contestantProperties.item(1).getFirstChild() != null) {
                    String bio = contestantProperties.item(1).getFirstChild().getNodeValue();
                }
    
                if (contestantProperties.item(2).getFirstChild() != null) {
                    String city = contestantProperties.item(2).getFirstChild().getNodeValue();
                }
                //ToDO: Extract the other properties of Contestant following pattern above
            }
        }
    }
    

    调用上述方法如下:parseContestants(xml);

    对于 JSON,解析和提取参赛者数据的示例代码(第 3 步):

    我们将使用 GSON,它是一个 Java 库,可用于将 JSON 字符串转换为等效的 Java 对象。

    通过将以下行添加到您的 build.gradle 文件中,将 GSON 添加到您的项目中:compile 'com.google.code.gson:gson:2.4'

    将以下Contestant 类添加到您的项目中:

    import com.google.gson.annotations.Expose;
    import com.google.gson.annotations.SerializedName;
    
    public class Contestant {
    
      @SerializedName("Age")
      @Expose
      private Integer Age;
      @SerializedName("Bio")
      @Expose
      private String Bio;
      @SerializedName("City")
      @Expose
      private String City;
      @SerializedName("ContestantID")
      @Expose
      private Integer ContestantID;
      @SerializedName("CurrentWeekPoints")
      @Expose
      private Integer CurrentWeekPoints;
      @SerializedName("FirstName")
      @Expose
      private String FirstName;
      @SerializedName("ImageURL")
      @Expose
      private String ImageURL;
      @SerializedName("LastName")
      @Expose
      private String LastName;
      @SerializedName("Occupation")
      @Expose
      private String Occupation;
      @SerializedName("State")
      @Expose
      private String State;
      @SerializedName("Status")
      @Expose
      private String Status;
      @SerializedName("TotalPoints")
      @Expose
      private Integer TotalPoints;
    
      public Integer getAge() {
        return Age;
      }
    
      public void setAge(Integer Age) {
        this.Age = Age;
      }
    
      public String getBio() {
        return Bio;
      }
    
      public void setBio(String Bio) {
        this.Bio = Bio;
      }
    
      public String getCity() {
        return City;
      }
    
      public void setCity(String City) {
        this.City = City;
      }
    
      public Integer getContestantID() {
        return ContestantID;
      }
    
      public void setContestantID(Integer ContestantID) {
        this.ContestantID = ContestantID;
      }
    
      public Integer getCurrentWeekPoints() {
        return CurrentWeekPoints;
      }
    
      public void setCurrentWeekPoints(Integer CurrentWeekPoints) {
        this.CurrentWeekPoints = CurrentWeekPoints;
      }
    
      public String getFirstName() {
        return FirstName;
      }
    
      public void setFirstName(String FirstName) {
        this.FirstName = FirstName;
      }
    
      public String getImageURL() {
        return ImageURL;
      }
    
      public void setImageURL(String ImageURL) {
        this.ImageURL = ImageURL;
      }
    
      public String getLastName() {
        return LastName;
      }
    
      public void setLastName(String LastName) {
        this.LastName = LastName;
      }
    
      public String getOccupation() {
        return Occupation;
      }
    
      public void setOccupation(String Occupation) {
        this.Occupation = Occupation;
      }
    
      public String getState() {
        return State;
      }
    
      public void setState(String State) {
        this.State = State;
      }
    
      public String getStatus() {
        return Status;
      }
    
      public void setStatus(String Status) {
        this.Status = Status;
      }
    
      public Integer getTotalPoints() {
        return TotalPoints;
      }
    
      public void setTotalPoints(Integer TotalPoints) {
        this.TotalPoints = TotalPoints;
      }
    }
    

    将以下Contestants 类添加到您的项目中:

    import com.google.gson.annotations.Expose;
    import com.google.gson.annotations.SerializedName;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class Contestants {
    
      @SerializedName("Contestants")
      @Expose
      private List<Contestant> Contestants = new ArrayList<Contestant>();
      @SerializedName("ResponseCode")
      @Expose
      private Boolean ResponseCode;
      @SerializedName("ResponseMessage")
      @Expose
      private String ResponseMessage;
    
      public List<Contestant> getContestants() {
        return Contestants;
      }
    
      public void setContestants(List<Contestant> Contestants) {
        this.Contestants = Contestants;
      }
    
      public Boolean getResponseCode() {
        return ResponseCode;
      }
    
      public void setResponseCode(Boolean ResponseCode) {
        this.ResponseCode = ResponseCode;
      }
    
      public String getResponseMessage() {
        return ResponseMessage;
      }
    
      public void setResponseMessage(String ResponseMessage) {
        this.ResponseMessage = ResponseMessage;
      }
    }
    

    以上类由jsonschema2pojo生成

    将 JSON 解析为等效的 Java 对象:

    private Contestants parseContestants(String json) {
        return new Gson().fromJson(json, Contestants.class);
    }
    

    AsyncTask 的示例代码(第 4 步):

    private class GetContestantsAsync extends AsyncTask<Void, Void, Void> {
    
        @Override
        protected void onPreExecute() {
        }
    
        @Override
        protected Void doInBackground(Void... params) {
            try {
    
                String xml = getContestants("Rjfk@vDV43F", "79C8RE30-ELJD-4617-VX2D-A374C8C59E3F");
                parseContestants(xml);
    
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    
        @Override
        protected void onPostExecute(Void result) {
        }
    }
    

    调用AsyncTask如下:

    GetContestantsAsync getContestantsAsync = new GetContestantsAsync();
        getContestantsAsync.execute();
    

    【讨论】:

    • 谢谢你的朋友,但是 webservice 以 json 格式接受 srequest 并以 json 格式给出响应。
    • 你试过上面的代码吗?我调用了您的 Web 服务,它返回了 xml。仅 Restful API 以 json 或 xml 格式返回数据。
    • 它给了我“UIOnmainthrea”异常
    • 请查看我对答案所做的编辑。我刚刚测试了我的代码,我可以成功调用 Web 服务并解析响应。
    • 非常感谢..但是我还有一个查询是我的同事正在使用相同的 web 服务并在目标 C 中以 json 格式获得响应。你能告诉我我该怎么做吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-29
    • 2017-07-30
    • 1970-01-01
    • 2012-08-20
    • 2010-11-04
    • 1970-01-01
    相关资源
    最近更新 更多