我看过关于这个问题的类似帖子,但没有一篇与使用 Visual Studio 开发服务器 for ASP .NET 相关。
我收到以下错误。
已建立的连接被主机中的软件中止。
我正在执行以下代码:
String employeesJson = client.downloadString("http://localhost:60000/Api/Employee/GetEmployees.aspx");
当我在常规网络浏览器(Chrome 21 或 Internet Explorer 10)中运行它时,它运行得很好。我得到了我想要的 JSON 结果。
我WebClient
正在使用的类(在变量“ client
”下)定义如下。
public class WebClient {
private HttpClient httpClient;
public WebClient() {
httpClient = new DefaultHttpClient();
}
public String downloadString(String url) throws IOException {
HttpGet get = new HttpGet(url);
try {
HttpResponse response = httpClient.execute(get); //this is where the error occurs.
HttpEntity entity = response.getEntity();
if(entity != null) {
InputStream stream = entity.getContent();
InputStreamReader streamReader = new InputStreamReader(stream);
BufferedReader bufferedReader = new BufferedReader(streamReader);
StringBuilder builder = new StringBuilder();
String line = null;
try {
while ((line = bufferedReader.readLine()) != null) {
builder.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return builder.toString();
}
//catch all the types of exceptions this method can throw. catching "Exception" is considered bad.
} catch (ClientProtocolException e) {
e.printStackTrace();
}
return null;
}
}
我的 AndroidManifest.xml 文件如下所示:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="specialisering.android"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="15" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>