如何从Android应用程序调用RESTful API(ASP.NET)?
我遵循了这里的教程:使用ASP.NET创建RESTful API,一切都很好。在本教程结束时,我下载了一个ZIP文件,其中包含一个Java文件,其中包含对API中方法的调用 问题是…我如何调用这些方法以便它们与我的web服务API交互?我真的很困惑,过去我在web服务器上使用PHP和插入/提取SQL数据做过类似的事情,但从未使用ASP.NET或类似的设置 如果有帮助的话,下面是我在该教程结束时得到的Java文件的内容:如何从Android应用程序调用RESTful API(ASP.NET)?,android,asp.net,json,rest,Android,Asp.net,Json,Rest,我遵循了这里的教程:使用ASP.NET创建RESTful API,一切都很好。在本教程结束时,我下载了一个ZIP文件,其中包含一个Java文件,其中包含对API中方法的调用 问题是…我如何调用这些方法以便它们与我的web服务API交互?我真的很困惑,过去我在web服务器上使用PHP和插入/提取SQL数据做过类似的事情,但从未使用ASP.NET或类似的设置 如果有帮助的话,下面是我在该教程结束时得到的Java文件的内容: public class RestAPI { private final S
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;
}
}
注意:displaySafeMessage()方法是从一个按钮onClick()调用的,我没有包含该方法。Android中没有此代码的错误,但也没有返回任何内容,我在Departments表中有值,如SQL查询所示
我知道我错过了一件大事,所以请告诉我是什么!
谢谢 您需要在AsycTask类中调用该方法。将URL字符串值更改为
”http://10.0.2.2:53749/Gen_Handler.ashx";
通过仿真器访问它。要通过真正的android设备访问API,您需要在公共托管空间中托管API。使用下面的代码调用.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();
}
}
导入android.content.Context;
import com.ayconsultancy.sumeshmedicals.R;
导入com.ayconsultancy.sumeshmedicals.utils.utils;
导入java.io.BufferedOutputStream;
导入java.io.BufferedReader;
导入java.io.DataOutputStream;
导入java.io.IOException;
导入java.io.InputStreamReader;
导入java.io.OutputStream;
导入java.io.OutputStreamWriter;
导入java.net.HttpURLConnection;
导入java.net.URL;
导入java.util.HashMap;
导入java.util.Map;
/**
*由Admin33于2015年12月30日创建。
*/
公共类RestClient{
//静态字符串ip=”http://192.168.1.220/SmartCure/api/";
静态语境;
专用静态int响应码;
私有静态字符串响应;
公共静态字符串getResponse(){
返回响应;
}
公共静态void setResponse(字符串响应){
RestClient.response=响应;
}
公共静态int getResponseCode(){
返回响应代码;
}
公共静态无效setResponseCode(int responseCode){
RestClient.responseCode=responseCode;
}
公共静态void Execute(字符串requestMethod、字符串jsonData、字符串urlMethod、上下文contextTemp、HashMap参数){
试一试{
context=contextTemp;
String ip=context.getResources().getString(R.String.ip);
StringBuilder urlString=新的StringBuilder(ip+urlMethod);
如果(参数!=null){
对于(Map.Entry段落:params.entrySet()){
if(para.getValue()instanceof Long){
追加(“?”+para.getKey()+”=“+(长)para.getValue());
}
if(para.getValue()instanceof String){
urlString.append(“?”+para.getKey()+“=”+String.valueOf(para.getValue());
}
}
}
URL=新URL(urlString.toString());
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
conn.setRequestMethod(requestMethod);
conn.setReadTimeout(10000/*毫秒*/);
conn.setConnectTimeout(15000/*毫秒*/);
开关(请求方法){
案例“POST”:案例“PUT”:
conn.setDoInput(真);
连接设置输出(真);
conn.setRequestProperty(“内容类型”,“应用程序/json;字符集=utf-8”);
conn.setRequestProperty(“X-request-With”,“XMLHttpRequest”);
连接();
OutputStream os=新的BufferedOutputStream(conn.getOutputStream());
write(jsonData.getBytes());
os.flush();
responseCode=conn.getResponseCode();
打破
案例“GET”:
responseCode=conn.getResponseCode();
System.out.println(“获取响应代码::”+响应代码);
打破
}
如果(responseCode==HttpURLConnection.HTTP_OK){//success
BufferedReader in=新的BufferedReader(新的InputStreamReader(
conn.getInputStream());
字符串输入线;
StringBuffer tempResponse=新的StringBuffer();
而((inputLine=in.readLine())!=null){
tempResponse.append(inputLine);
}
in.close();
response=tempResponse.toString();
System.out.println(response.toString());
}否则{
System.out.println(“获取请求未工作”);
}
}捕获(IOE异常){
e、 printStackTrace();
}
}
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();
}
}