![](/img/trans.png)
[英]Im trying to recreate this C# code in java to call my web api make i ASP.NET
[英]I'm trying to call a web api (that i made in ASP.NET) in java (android)
这是我的代码:
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
String url="10.152.2.45";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private class ListarEventos extends AsyncTask<String, Void, ArrayList<Evento>> {
private OkHttpClient client = new OkHttpClient();
@Override
protected void onPostExecute(ArrayList<Evento> direcciones) {
super.onPostExecute(direcciones);
}
@Override
protected ArrayList<Evento> doInBackground(String... params) {
Request request = new Request.Builder()
.url(url)
.build();
try {
Response response = client.newCall(request).execute();
return parseResult(response.body().string());
} catch (IOException | JSONException e) {
Log.d("Error",e.getMessage());
return new ArrayList<Evento>();
}
}
ArrayList<Evento> parseResult(String JSONstr) throws JSONException {
ArrayList<Evento> eventos = new ArrayList<>();
JSONObject json = new JSONObject(JSONstr);
JSONArray jsonEventos = json.getJSONArray("results");
Date result=new Date ();
for (int i=0; i<jsonEventos.length(); i++) {
JSONObject jsonResultado = jsonEventos.getJSONObject(i);
int jsonId = jsonResultado.getInt("Id");
String jsonMat = jsonResultado.getString("Materia");
String jsonTipo = jsonResultado.getString("Tipo");
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH");
String Fecha=jsonResultado.getString("Fecha");
try {
result = df.parse(Fecha);
}catch (Exception e) {
}
String jsonDesc = jsonResultado.getString("Descripcion");
Evento d = new Evento();
d.Id=jsonId;
d.Materia=jsonMat;
d.Tipo=jsonTipo;
d.Fecha=result;
d.Descripcion=jsonDesc;
eventos.add(d);
}
return eventos;
}
}
}
首先,我不知道如何调用该服务,如果我写了 IP 地址,它就不起作用,因为我在调试 API 的同时调试了 android(在同一台计算机上)。 代码应该做的是调用 API,转到 localhost/api/Eventos/Get 并获取包含所有事件的 json。
PS:我写的是电脑IP因为如果我写localhost就不行
要调用在您的机器上运行的 Web API,您需要知道它的确切 url - 仅 localhost 或您的 IP 是不够的,您应该指定它正在运行的端口及其端点,例如localhost:8080/myapi
此外,您应该知道 API 需要什么样的请求 - 它是否需要 GET、POST 或其他类型的请求? 你需要传递什么参数?
当您在本地启动 Web 服务时,您应该能够找到有关该服务的信息。 此外,调用方(在本例中为您的 Android 应用程序)使用哪种语言开发 Web 服务也没有区别 - 它可以用除 ASP.NET 之外的任何其他语言编写并且行为相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.