问题描述
我一直在尝试从Android设备连接到WCF服务。我读过很多看似没用的博客。在我的WCF上运行的一个操作是 -
I have been attempting to to connect to a WCF Service from a Android device. I have read a lot of blogs that does not seem to be useful. One of the Operations running on my WCF is -
[OperationContract]
[WebGet(UriTemplate = "write", ResponseFormat = WebMessageFormat.Json)]
string write();
这将一个实体写入数据库。当我在手机浏览器10.0.0.14/serv/UserManagement.svc/write中输入URL时,我收到相关消息并且写入数据库没有问题。当我尝试从Android应用程序中使用WCF时出现问题。
我跳过了许多不同的解决方案类型,我目前正在使用
This writes one entity to a database. When I enter the URL in my phones browser "10.0.0.14/serv/UserManagement.svc/write" I get the relevant message and it writes to the database with no problem. The problem arises when I attempt to Consume the WCF from a android application.
I have jumped between many different solution types and I am currently using
try
{
DefaultHttpClient httpClient = new DefaultHttpClient();
URI uri = new URI("http://10.0.0.14/serv/UserManagement.svc/write");
HttpGet httpget = new HttpGet(uri);
httpget.setHeader("Accept", "application/json");
httpget.setHeader("Content-type", "application/json; charset=utf-8");
HttpResponse response = httpClient.execute(httpget);
HttpEntity responseEntity = response.getEntity();
}
catch (Exception e)
{
e.printStackTrace();
}
这不起作用。我已将< uses-permission android:name =android.permission.INTERNETxmlns:android =#unknown/>
添加到我的清单中。
在我的LogCat中有一个 NetworkOnMainThreadException 。
我该如何解决这个问题?
This does not work. I have added <uses-permission android:name="android.permission.INTERNET" xmlns:android="#unknown" />
to my manifest.
In my LogCat there is a NetworkOnMainThreadException.
How can I fix the problem?
推荐答案
class ConnectToWCF extends AsyncTask<void,> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(Void... arg0) {
String is = "";
try
{
DefaultHttpClient httpClient = new DefaultHttpClient();
URI uri = new URI("http://10.0.0.14/serv/UserManagement.svc/write");
HttpGet httpget = new HttpGet(uri);
httpget.setHeader("Accept", "application/json");
httpget.setHeader("Content-type", "application/json; charset=utf-8");
HttpResponse response = httpClient.execute(httpget);
HttpEntity responseEntity = response.getEntity();
}
catch (Exception e)
{
e.printStackTrace();
}
return is;
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
并在主线程中使用它,即onCreate
and use it in your main thread i.e onCreate
new ConnectToWCF().execute();
这篇关于使用Android消耗Restful WCF服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!