Android使用JSON想服務器發送數據

final String urlPath=”https://60.123.36.163:8080/wms/resisteruser.do”;
URL url;
try
{
url = new URL(urlPath);
/*封裝子對象*/
JSONObject ClientKey = new JSONObject();
ClientKey.put(“appusername”, userName.getText().toString());
ClientKey.put(“eigenvalues”, passWord.getText().toString());
ClientKey.put(“telephone”, phoneNum.getText().toString());
ClientKey.put(“apprealname”, realName.getText().toString());
ClientKey.put(“email”, emailNum.getText().toString());
ClientKey.put(“sex”, sex);

/*封裝Person數組*/
JSONObject params = new JSONObject();
params.put(“Person”, ClientKey);
/*把JSON數據轉換成String類型使用輸出流向服務器寫*/
String content = String.valueOf(params);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setDoOutput(true);//設置允許輸出
conn.setRequestMethod(“POST”);
conn.setRequestProperty(“User-Agent”, “Fiddler”);
conn.setRequestProperty(“Content-Type”, “application/json”);
OutputStream os = conn.getOutputStream();
os.write(content.getBytes());
os.close();

/*服務器返回的響應碼*/
int code = conn.getResponseCode();
if(code == 1)
{
Toast.makeText(Register.this, “恭喜您註冊成功!”, Toast.LENGTH_SHORT).show();
Intent intentToLogin=new Intent();
intentToLogin.setClass(Register.this,Login.class);
startActivity(intentToLogin);
}

}
catch (Exception e)
{
e.printStackTrace();
}

發佈留言