我在 C# 中有一个 WebService,它使用 webapi 并通过一个 url 提供一个 json ,直到确定为止。
public class UsuarioByGroupController : ApiController
{
// GET api/getusuariobygroup
public List<DTOUsuario> Get()
{
int valor = 0;
return new RepUsuario().GetUsuarioByGrupo(6, 0, int.MaxValue, null, null, out valor).ToList();
}
在android中,我有一个“获取”传递url的WebService的方法(此方法适用于另一个应用程序):
private static final String URI = "http://10.0.2.2:3671/api/";
public static <T> T get(String url, T e) throws Exception {
String[] json = new WebService().get(URI + url);
List<T> obj = new ArrayList<T>();
if (json[0].equals("200")) {
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonArray array = parser.parse(json[1]).getAsJsonArray();
for (int i = 0; i < array.size(); i++) {
obj.add(gson.fromJson(array.get(i), (Class<T>) e));
}
return (T) obj;
} else {
throw new Exception(json[1]);
}
}
但它返回给我以下内容:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Bad Request</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Bad Request - Invalid Hostname</h2>
<hr><p>HTTP Error 400. The request hostname is invalid.</p>
</BODY></HTML>
编辑:
public final String[] get(String url) {
String[] result = new String[2];
HttpGet httpget = new HttpGet(url);
HttpResponse response;
try {
response = HttpClientSingleton.getHttpClientInstace().execute(
httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
result[0] = String.valueOf(response.getStatusLine()
.getStatusCode());
InputStream instream = entity.getContent();
result[1] = toString(instream);
instream.close();
}
} catch (Exception e) {
Log.e("NGVL", "Falha ao acessar Web service", e);
result[0] = "0";
result[1] = "Falha na rede!";
}
return result;
}