java在Android上从Web API检索JSON
这里。。。我有一个带有MessageController的Web API,它将响应我来自Android的请求并发送JSON(Hello World-只是为了测试一下)
public class MessageController : ApiController
{
public async Task<IHttpActionResult> SendAsync()
{
return Ok(new { text = "hello world" });
}
}
从我的Android应用程序中,我想从API中请求JSON。我已经从其他Web API(如currency等)请求过了,但同样的方法在我的API上不起作用
这是:
public void requestMessagesFromApi(View v)
throws ClientProtocolException, IOException {
final String response = getJSON(finalUrl);
TextView msgTV = (TextView) findViewById(R.id.msgTxt);
msgTV.setText(response);
}
public String getJSON(String url) {
HttpURLConnection c = null;
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-length", "0");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
return sb.toString();
}
} catch (MalformedURLException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
return null;
}
我得到了代码-1的回复。不知道为什么。在最终URL中,我将我的Web API定位在Azure上:
finalUrl ="http://<hereIsMineWebApiURL>/api/message"
我确信我的API是错的
共 (0) 个答案