如何从Android App调用RESTful API(ASP.NET)?

时间:2014-03-21 22:48:04

标签: android asp.net json rest

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

问题是......如何调用这些方法以便它们与我的Web服务API进行交互?我真的很困惑,我以前在我的网络服务器上使用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查询显示。

我知道我在这里遗漏了一件大事,所以请让我知道它是什么! 谢谢!

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

使用下面的代码来调用.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();
        }

    }