Reputation: 1029
In activity there are two edit text to get username and password and one button for the action. Here is Listener code.
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());
}
}
});
Here is the makeRequest function:
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);
}
Here the WCF file:
namespace MyWCFSolution
{
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "Check")]
String CheckSQL(string getJson);
}
}
How can I connect the wcf server to android using Json. I want to send Json object which includes username and password and response with json object which includes username, password, name, and surname. But I have trouble in that point. I can't connect the host and can't Post and Get json data. Does anybody can explain clearly? (example codes, comments)
Upvotes: 0
Views: 1906
Reputation: 2947
I've made something a time ago, almost like the solution you need.
I don't know if it was the best workaround, but it worked perfectly
On your method, first of all, if you want to receive a JSON, "GET" is not the best option, try POST, because URL QueryString has a character limit, and if your JSON is big, it will not enter there
Second, I've declared a POCO Object in Net, that matches exactly with the JSON structure, and then I've declare on the method that it has to receive that object.
ITS IMPORTANT that the keys on your json matchs exactly with the POCO Object properties, is key sensitive
IIS parsed automatically the JSON posted from Android, to that POCO Object in Net, so it worked like magic, nothing to parse, clean object received.
Of course check if your URI Templates are OK, because if it's not OK, you will never receive the request on yor WCF server.
Other thing: In your Android APP, you are sending the JSON as a POST Request. In your WCF your method is waiting a GET request.
Upvotes: 0
Reputation: 1633
Go through this articles,
http://www.vogella.com/articles/AndroidJSON/article.html
http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
ObjectMapper mapper = new ObjectMapper();
ArrayList<RespuestaEncuesta> respuestas = new ArrayList<RespuestaEncuesta>(1);
RespuestaEncuesta r = new RespuestaEncuesta();
r.Comentarios = "ASD";
r.GrupoClienteID = UUID.fromString("00000000-0000-0000-0000-000000000000");
r.GrupoID = 1155;
r.Opcion = "2";
respuestas.add(r);
RespuestaWrapper data = new RespuestaWrapper();
data.Respuestas = respuestas;
mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
String respuestarJson = mapper.writeValueAsString(data);
String url = config[0] + "/GuardaEncuestas";
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
StringEntity tmp = new StringEntity(respuestarJson);
httpPost.setEntity(tmp);
DefaultHttpClient httpClient = new DefaultHttpClient();
httpClient.execute(httpPost);
Hope it will be hlepful
Upvotes: 1