我是Android程序员的新手,我希望以下列格式通过JSON向服务器发送数据,并以这种格式实现Json ......还想从服务器获取数据..
{
"signup": [
{
"username": "test1264",
"password": "1234",
"email": "example@gmail.com",
"phoneno": "223344556",
"altphoneno": "12345678",
"firstname": "abc",
"lastname": "xyz"
} ]
}
响应:
成功:
{"status":1}
失败时:{"status":0}
{"login":[
{"username":"test1234",
"password":"1234"}
]}
Response:
on success: {
"user": [
{
"firstname": "abc",
"lastname": "xyz",
"email": "example@gmail.com",
"phone": "99887766",
"username": "test1234"
}
]
}
失败时:{"error":["Auth error"]}
答案 0 :(得分:3)
您可以使用此类代码
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://fort.example.com");
JSONObject json = new JSONObject();
try {
// Add your data
json.put("key", "value");
StringEntity se = new StringEntity( json.toString());
httppost.setEntity(se);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String jsonString = reader.readLine();
JSONTokener tokener = new JSONTokener(jsonString);
JSONObject finalResult = new JSONObject(tokener);
不要忘记将此添加到nonUI线程。
答案 1 :(得分:2)
您可以使用droidQuery轻松完成此操作:
$.ajax(new AjaxOptions().url("http://fort.example.com")
.type("POST")
.data("\"signup\": [{" +
"\"username\": \"test1264\"," +
"\"password\": \"1234\"," +
"\"email\": \"example@gmail.com\"," +
"\"phoneno\": \"223344556\"," +
"\"altphoneno\": \"12345678\"," +
"\"firstname\": \"abc\"," +
"\"lastname\": \"xyz\"" +
"\"}]")
.dataType("json")
.success(new Function() {
@Override
public void invoke($ d, Object... args) {
JSONObject json = (JSONObject) args[0];
boolean success = json.getBoolean("status");
if (success) {
//handle success
}
else {
//handle error
}
}
})
.error(new Function() {
@Override
public void invoke($ d, Object... args) {
AjaxError error = (AjaxError) args[0];
Log.i("Ajax", "Error " + error.status + ": " + error.reason);
}
}));
您可以针对其他情况重复此逻辑,例如您的登录Web服务。
答案 2 :(得分:0)
PostMethod method = new PostMethod();
org.apache.commons.httpclient.URI newUri = new org.apache.commons.httpclient.URI(URIstring, true);
method.setURI(newUri);
method.setRequestBody(JsonObj().toString());
method.setRequestHeader("Content-Type", "application/json");
org.apache.commons.httpclient.HttpClient newhttpClient = new org.apache.commons.httpclient.HttpClient();
int statusCode = newhttpClient.executeMethod(method);
return method.getResponseBodyAsString();