Android利用JSON發送資料到伺服器

來源:互聯網
上載者:User

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();

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.