在活动中,有两个用于获取用户名和密码的编辑文本以及一个用于操作的按钮。这是侦听器代码。
Button sendBtn = (Button) findViewById(R.id.sendBtn);
sendBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
EditText un = (EditText) findViewById(R.id.usernameEditText);
EditText pas = (EditText) findViewById(R.id.passwordEditText);
HttpResponse response = null;
user_name = un.getText().toString();
password = pas.getText().toString();
path = p + user_name;
my_map = createMap();
JSONObject ob=null;
try {
ob = new JSONObject("{\"Username\":user_name,\"Password\":password}");
} catch (JSONException e1) {
e1.printStackTrace();
}
try {
response = makeRequest(path, my_map,ob);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "utf-8"));
String json = reader.readLine();
JSONTokener tokener = new JSONTokener(json);
JSONArray finalResult = new JSONArray(tokener);
} catch (Exception e) {
Log.e("HTTP ERROR", e.toString());
}
}
});
这是 makeRequest 函数:
public static HttpResponse makeRequest(String path, Map params,JSONObject obj) throws Exception
{
DefaultHttpClient httpclient = null;
HttpPost httpost = null;
ResponseHandler responseHandler = null;
//instantiates httpclient to make request
httpclient = new DefaultHttpClient();
//url with the post data
HttpGet httpget = new HttpGet(path);
httpost = new HttpPost(path);
//convert parameters into JSON object
JSONObject holder = obj;
//passes the results to a string builder/entity
StringEntity se = new StringEntity(holder.toString(), HTTP.UTF_8);
//sets the post request as the resulting string
httpost.setEntity(se);
//sets a request header so the page receving the request
//will know what to do with it
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/json");
try{
//Handles what is returned from the page
responseHandler = new BasicResponseHandler();
}catch(Exception e){
Log.e("HTTP ERROR", e.toString());
}
return httpclient.execute(httpost, responseHandler);
}
这里是 WCF 文件:
namespace MyWCFSolution
{
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "Check")]
String CheckSQL(string getJson);
}
}
如何使用 Json 将 wcf 服务器连接到 android。我想发送包含用户名和密码的 Json 对象以及包含用户名、密码、姓名和姓氏的 json 对象的响应。但我在这一点上遇到了麻烦。我无法连接主机,无法发布和获取 json 数据。有人能解释清楚吗?(示例代码、注释)