Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android利用JSON發送數據到服務器

Android利用JSON發送數據到服務器

編輯:關於Android編程

new Thread()
{


@Override
public void run() {
// TODO Auto-generated method stub
Looper.prepare();
final String urlPath="http://60.176.36.125:8080/wms/resisteruser.do";
URL url;
try
{
url = new URL(urlPath);
/*封裝子對象*/
JSONObject ClientKey = new JSONObject();
ClientKey.put("appusername", userName.getText().toString());
ClientKey.put("passwd", passWord.getText().toString());
ClientKey.put("eigenvalues", eigenValues.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");
conn.setRequestProperty("Charset", encoding);
OutputStream os = conn.getOutputStream();
os.write(content.getBytes());
os.close();
/*服務器返回的響應碼*/
int code = conn.getResponseCode();
if(code == 200)
{
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), encoding));
String retData = null;
String responseData = "";
while((retData = in.readLine()) != null)
{
responseData += retData;
}
JSONObject jsonObject = new JSONObject(responseData);
JSONObject succObject = jsonObject.getJSONObject("regsucc");
//System.out.println(result);
String success = succObject.getString("id");

in.close();
//System.out.println(success);
Toast.makeText(Register.this, success, Toast.LENGTH_SHORT).show();
Intent intentToLogin=new Intent();
intentToLogin.setClass(Register.this,Login.class);
startActivity(intentToLogin);
finish();
}
else
{
Toast.makeText(getApplicationContext(), "數據提交失敗", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
// TODO: handle exception
throw new RuntimeException(e);
}
Looper.loop();
}

}.start();
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved