[英]Calling Asp.net web API from Android Studio View
通過android studio項目訪問asp.net Web API時遇到問題。 我的Web API通過實體框架與數據庫連接。 我想通過android商人視圖通過API Merchant Controller調用商人列表。 這是我的商人的HttpGet方法:
public class MerchantController : ApiController
{
private DostiCardDBEntities merchantEntities = new DostiCardDBEntities();
[HttpGet]
public HttpResponseMessage listOfMerchant() {
return Request.CreateResponse(HttpStatusCode.OK, merchantEntities.MerchantTables.ToList());
}
}
我通過AsyncTask doInBackground方法訪問商家列表,即
private class ExecuteTask extends AsyncTask<String, Integer, String>{
String jsonText = "";
HttpsURLConnection connection;
@Override
protected String doInBackground(String... strings) {
try {
URL url = new URL("http://169.254.80.80:6040/api/Merchant");
connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
InputStream inputStream = connection.getInputStream();
int byteCharacter;
while ((byteCharacter = inputStream.read()) != -1){
char c = (char) byteCharacter;
jsonText += c;
}
} catch (IOException e) {
e.printStackTrace();
}
finally {
connection.disconnect();
}
return null;
}
@Override
protected void onPostExecute(String s) {
Toast.makeText(getApplicationContext(), jsonText, Toast.LENGTH_LONG).show();
}
}
默認情況下, localhost
外部無法訪問C#Web Api,即在您的LAN網絡中。 您要做的是轉到項目路徑,並且在項目文件夾中有一個名為.vs
文件夾,默認情況下該文件夾.vs
隱藏狀態(您可以通過更改文件夾和搜索選項設置來看到該文件夾)。
現在打開.vs
文件夾和goto config
文件夾,並使用任何文本編輯器打開applicationhost.xml
文件。
打開后找出以下行
<bindings>
<binding protocol="http" bindingInformation="*:6040:localhost" />
</bindings>
並像這樣更新上面的行
<bindings>
<binding protocol="http" bindingInformation="*:6040:localhost" />
<binding protocol="http" bindingInformation="*:6040:*" />
</bindings>
其中, 6040
是您的項目的端口地址。 保存並退出編輯器。 現在,這使您可以在整個LAN連接中訪問Web Api。 (有時您必須使用Admin Privileges啟動Visual Studio)。
現在,在您的手機中打開任何瀏覽器,然后輸入如下地址
http://169.254.80.80:6040
如果您從api得到一些響應,則可以正常工作。
您可以檢查這是您的公共IP,還是檢查它是否可以在您的域之外訪問(因為您的設備應該在您的域之外),還可以檢查清單中是否已授予Internet訪問權限。
您應該將HttpsURLConnection更改為HttpURLConnection,因為使用協議http而不是https的URL
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.