【问题标题】:How to call a RESTful API (ASP.NET) from Android App?如何从 Android App 调用 RESTful API (ASP.NET)?
【发布时间】:2014-04-29 12:50:04
【问题描述】:

我按照这里的教程:http://www.tutecentral.com/restful-api-for-android-part-1/ 使用 ASP.NET 创建了一个 RESTful API,一切都很好。在教程结束时,我下载了一个 ZIP 文件,其中包含一个 Java 文件,其中调用了 API 中的方法。

问题是...如何调用这些方法以便它们与我的 Web 服务 API 交互?我真的很困惑,我过去在我的 Web 服务器上使用 PHP 并插入/提取 SQL 数据做过类似的事情,但从来没有使用 ASP.NET 或类似的设置。

如果有帮助,以下是我在该教程结束时获得的 Java 文件的内容:

public class RestAPI {
private final String urlString = "http://localhost:53749/Gen_Handler.ashx";

private static String convertStreamToUTF8String(InputStream stream) throws IOException {
    String result = "";
    StringBuilder sb = new StringBuilder();
    try {
        InputStreamReader reader = new InputStreamReader(stream, "UTF-8");
        char[] buffer = new char[4096];
        int readChars = 0;
        while (readChars != -1) {
            readChars = reader.read(buffer);
            if (readChars > 0)
               sb.append(buffer, 0, readChars);
        }
        result = sb.toString();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return result;
}

private String load(String contents) throws IOException {
    URL url = new URL(urlString);
    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
    conn.setRequestMethod("POST");
    conn.setConnectTimeout(60000);
    conn.setDoOutput(true);
    conn.setDoInput(true);
    OutputStreamWriter w = new OutputStreamWriter(conn.getOutputStream());
    w.write(contents);
    w.flush();
    InputStream istream = conn.getInputStream();
    String result = convertStreamToUTF8String(istream);
    return result;
}

private Object mapObject(Object o) {
    Object finalValue = null;
    if (o.getClass() == String.class) {
        finalValue = o;
    }
    else if (Number.class.isInstance(o)) {
        finalValue = String.valueOf(o);
    } else if (Date.class.isInstance(o)) {
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss", new Locale("en", "USA"));
        finalValue = sdf.format((Date)o);
    }
    else if (Collection.class.isInstance(o)) {
        Collection<?> col = (Collection<?>) o;
        JSONArray jarray = new JSONArray();
        for (Object item : col) {
            jarray.put(mapObject(item));
        }
        finalValue = jarray;
    } else {
        Map<String, Object> map = new HashMap<String, Object>();
        Method[] methods = o.getClass().getMethods();
        for (Method method : methods) {
            if (method.getDeclaringClass() == o.getClass()
                    && method.getModifiers() == Modifier.PUBLIC
                    && method.getName().startsWith("get")) {
                String key = method.getName().substring(3);
                try {
                    Object obj = method.invoke(o, null);
                    Object value = mapObject(obj);
                    map.put(key, value);
                    finalValue = new JSONObject(map);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
    return finalValue;
}

public JSONObject CreateNewAccount(String firstName,String lastName,String userName,String password) throws Exception {
    JSONObject result = null;
    JSONObject o = new JSONObject();
    JSONObject p = new JSONObject();
    o.put("interface","RestAPI");
    o.put("method", "CreateNewAccount");
    p.put("firstName",mapObject(firstName));
    p.put("lastName",mapObject(lastName));
    p.put("userName",mapObject(userName));
    p.put("password",mapObject(password));
    o.put("parameters", p);
    String s = o.toString();
    String r = load(s);
    result = new JSONObject(r);
    return result;
}

public JSONObject GetUserDetails(String userName) throws Exception {
    JSONObject result = null;
    JSONObject o = new JSONObject();
    JSONObject p = new JSONObject();
    o.put("interface","RestAPI");
    o.put("method", "GetUserDetails");
    p.put("userName",mapObject(userName));
    o.put("parameters", p);
    String s = o.toString();
    String r = load(s);
    result = new JSONObject(r);
    return result;
}

public JSONObject UserAuthentication(String userName,String passsword) throws Exception {
    JSONObject result = null;
    JSONObject o = new JSONObject();
    JSONObject p = new JSONObject();
    o.put("interface","RestAPI");
    o.put("method", "UserAuthentication");
    p.put("userName",mapObject(userName));
    p.put("passsword",mapObject(passsword));
    o.put("parameters", p);
    String s = o.toString();
    String r = load(s);
    result = new JSONObject(r);
    return result;
}

public JSONObject GetDepartmentDetails() throws Exception {
    JSONObject result = null;
    JSONObject o = new JSONObject();
    JSONObject p = new JSONObject();
    o.put("interface","RestAPI");
    o.put("method", "GetDepartmentDetails");
    o.put("parameters", p);
    String s = o.toString();
    String r = load(s);
    result = new JSONObject(r);
    return result;
}
}

在我的活动/片段中,我尝试这样做,但没有返回任何内容:(。

public void displaySafeMessage(View view) {
        RestAPI test = new RestAPI();
        JSONObject jsonObj = new JSONObject();

        try {
            //jsonObj = test.CreateNewAccount("tudor","hofnar","tudor.hofnar","password");
            jsonObj = test.GetDepartmentDetails();
        } catch (Exception e) {
        }

        String tmp = jsonObj.toString();
        Toast.makeText(getActivity(), tmp, Toast.LENGTH_LONG).show();
    }

注意:displaySafeMessage() 方法是从我没有包含的按钮 onClick() 调用的。此代码在 Android 中没有错误,但也没有返回任何内容,并且我在 Departments 表中有值,作为SQL 查询显示。

我知道我在这里遗漏了一件重要的事情,所以请告诉我它是什么! 谢谢!

【问题讨论】:

    标签: android asp.net json rest


    【解决方案1】:

    您需要调用 AsycTask 类中的方法。将 urlString 值更改为 "http://10.0.2.2:53749/Gen_Handler.ashx"; 以通过模拟器访问它。要通过真正的 android 设备访问 API,您需要将 API 托管在公共托管空间中。

    【讨论】:

      【解决方案2】:

      使用下面的代码调用.net restful webservice

      import android.content.Context;
      
      import com.ayconsultancy.sumeshmedicals.R;
      import com.ayconsultancy.sumeshmedicals.utils.Utils;
      
      import java.io.BufferedOutputStream;
      import java.io.BufferedReader;
      import java.io.DataOutputStream;
      import java.io.IOException;
      import java.io.InputStreamReader;
      import java.io.OutputStream;
      import java.io.OutputStreamWriter;
      import java.net.HttpURLConnection;
      import java.net.URL;
      import java.util.HashMap;
      import java.util.Map;
      
      /**
       * Created by Admin33 on 30-12-2015.
       */
      public class RestClient {
          //  static String ip = "http://192.168.1.220/SmartCure/api/";
          static Context context;
          private static int responseCode;
          private static String response;
      
          public static String getResponse() {
              return response;
          }
      
          public static void setResponse(String response) {
              RestClient.response = response;
          }
      
          public static int getResponseCode() {
              return responseCode;
          }
      
          public static void setResponseCode(int responseCode) {
              RestClient.responseCode = responseCode;
          }
      
          public static void Execute(String requestMethod, String jsonData, String urlMethod, Context contextTemp, HashMap<String, Object> params) {
              try {
                  context = contextTemp;
                  String ip = context.getResources().getString(R.string.ip);
                  StringBuilder urlString = new StringBuilder(ip + urlMethod);
                  if (params != null) {
                      for (Map.Entry<String, Object> para : params.entrySet()) {
                          if (para.getValue() instanceof Long) {
                              urlString.append("?" + para.getKey() + "=" +(Long)para.getValue());
                          }
                          if (para.getValue() instanceof String) {
                              urlString.append("?" + para.getKey() + "=" +String.valueOf(para.getValue()));
                          }
                      }
                  }
      
                  URL url = new URL(urlString.toString());
      
                  HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                  conn.setRequestMethod(requestMethod);
                  conn.setReadTimeout(10000 /*milliseconds*/);
                  conn.setConnectTimeout(15000 /* milliseconds */);
      
      
                  switch (requestMethod) {
                      case "POST" : case "PUT":
                          conn.setDoInput(true);
                          conn.setDoOutput(true);
                          conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
                          conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
                          conn.connect();
                          OutputStream os = new BufferedOutputStream(conn.getOutputStream());
                          os.write(jsonData.getBytes());
                          os.flush();
                          responseCode = conn.getResponseCode();
                          break;
                      case "GET":
                          responseCode = conn.getResponseCode();
                          System.out.println("GET Response Code :: " + responseCode);
                          break;
      
      
                  }
                  if (responseCode == HttpURLConnection.HTTP_OK) { // success
                      BufferedReader in = new BufferedReader(new InputStreamReader(
                              conn.getInputStream()));
                      String inputLine;
                      StringBuffer tempResponse = new StringBuffer();
      
                      while ((inputLine = in.readLine()) != null) {
                          tempResponse.append(inputLine);
                      }
                      in.close();
                      response = tempResponse.toString();
                      System.out.println(response.toString());
                  } else {
                      System.out.println("GET request not worked");
                  }
              } catch (IOException e) {
                  e.printStackTrace();
              }
      
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-05-12
        • 2018-09-01
        • 2017-08-07
        • 2011-08-28
        • 2011-08-28
        • 2020-10-04
        • 2016-06-22
        • 2018-12-30
        相关资源
        最近更新 更多