我创建了一个由android使用的WCF服务。它在json中返回DataRows。如,
的Web.config
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" strict="false" explicit="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5"/>
</system.web>
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="httpBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="WcfAndroid.Service1">
<endpoint address=""
behaviorConfiguration="httpBehavior"
binding="webHttpBinding"
contract="WcfAndroid.IService1" />
</service>
</services>
<protocolMapping>
<add binding="webHttpBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
服务接口IService1:
<OperationContract()> _
<WebInvoke(Method:="POST", UriTemplate:="GetEmp", ResponseFormat:=WebMessageFormat.Json)> _
Function GetEmp(ByVal EmpId As String) As DataTable
服务类服务1:
Public Function GetEmp(ByVal EmpId As String) As DataTable
Dim table As New DataTable("mytable")
table.Columns.Add("Result", GetType(String))
table.Columns.Add("acc", GetType(String))
table.Columns.Add("name", GetType(String))
table.Columns.Add("paid", GetType(Double))
'' Using EmpId for Fetching data from Database
table.Rows.Add("True", "1", "Employee1", 5000)
table.Rows.Add("True", "2", "Employee2", 2000)
Return table
End Function
EmpId是每位员工的唯一ID。我从Sql Server数据库中获取详细信息。为了测试,我手动发送了2行。
在 WebGet 的Android应用中,我使用过:
public static JSONObject requestWebService(String serviceUrl) {
HttpURLConnection urlConnection = null;
try {
URL urlToRequest = new URL(serviceUrl);
urlConnection = (HttpURLConnection)
urlToRequest.openConnection();
int statusCode = urlConnection.getResponseCode();
if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
// handle unauthorized
} else if (statusCode != HttpURLConnection.HTTP_OK) {
// handle any other errors
}
InputStream in = new BufferedInputStream(
urlConnection.getInputStream());
String ss=getResponseText(in);
return new JSONObject(ss);
} catch (MalformedURLException e) {
// URL is invalid
} catch (SocketTimeoutException e) {
// data retrieval or connection timed out
} catch (IOException e) {
// could not read response body
// (could not create input stream)
} catch (JSONException e) {
// response body is no valid JSON string
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
但我不知道如何使用EmpId和getDataRows进行POST。
我必须在Android应用程序中使用此服务。我正在使用HttpURLConnection。
如何使用HttpURLConnection和getDatarows(json格式)发布?
答案 0 :(得分:1)
您可以将OutputStreamWriter用作:
public static JSONObject PostWebService(String serviceUrl) {
HttpURLConnection urlConnection = null;
try {
// create connection
URL urlToRequest = new URL(serviceUrl);
urlConnection = (HttpURLConnection)
urlToRequest.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
out.write("EmpID2016");
// You can write json also // Uncomment
// JSONObject jsonParam = new JSONObject();
// jsonParam.put("EmpID", "25");
// jsonParam.put("description", "Employer");
// jsonParam.put("authorized", "true");
// out.write(jsonParam.toString());
out.close();
int statusCode = urlConnection.getResponseCode();
if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
// handle unauthorized (if service requires user login)
} else if (statusCode != HttpURLConnection.HTTP_OK) {
// handle any other errors, like 404, 500,..
}
// create JSON object from content
InputStream in = new BufferedInputStream(
urlConnection.getInputStream());
String ss=getResponseText(in);
return new JSONObject(ss);
} catch (MalformedURLException e) {
} catch (SocketTimeoutException e) {
} catch (IOException e) {
} catch (JSONException e) {
// response body is no valid JSON string
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}