android連線SSM傳送和接收資料
阿新 • • 發佈:2018-12-29
//註冊賬戶 URL url=null; HttpURLConnection httpURLConnection=null; String result=null,re=""; BufferedReader bufferedReader=null; int y=0,l=0; Intent intent1 = new Intent("com.example.space.text2.action.RECEIVER_REGISTER"); String email = intent.getStringExtra("email"); String password = intent.getStringExtra("password"); //連線網路進行註冊 try{ url = new URL("http://192.168.137.1:8080/SSM5/adduser.json"); }catch(MalformedURLException e) { intent1.putExtra("registerstate","網路連線失敗"); } try{ httpURLConnection =(HttpURLConnection)url.openConnection(); try{ httpURLConnection.setRequestMethod("POST"); }catch(ProtocolException g) { l=httpURLConnection.getResponseCode(); intent1.putExtra("registerstate","httpURLConnection.setRequestMethod(\"POST\")失敗"+String.valueOf(l)); } httpURLConnection.setReadTimeout(5000); httpURLConnection.setConnectTimeout(5000); httpURLConnection.setDoInput(true); httpURLConnection.setDoOutput(true); httpURLConnection.setInstanceFollowRedirects(true); BufferedWriter bufferedWriter=null; OutputStream outputStream = httpURLConnection.getOutputStream(); try{ bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8")); //bufferedWriter.write(jsonout.toString()); bufferedWriter.write("email="+email+"&"+"password="+password); }catch(IOException o){ Log.i("mss","bufferedWriter.write IOException"); } bufferedWriter.flush(); bufferedWriter.close(); outputStream.close(); JSONObject jsonObject = null; try{ result = httpURLConnection.getResponseMessage(); bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream())); }catch(IOException h) { intent1.putExtra("registerstate","httpURLConnection.getResponseMessage();失敗"); } String line; try{ while((line=bufferedReader.readLine())!=null) { re+=line; } }catch(IOException e){ intent1.putExtra("registerstate","bufferedReader.readLine()失敗"); } Log.i("mss",re); try{ JSONObject jsonObject1 = new JSONObject(re); if(jsonObject1.getInt("status")==1) { //註冊成功 intent1.putExtra("registerstate","註冊成功"); } else{ intent1.putExtra("registerstate","註冊失敗"); } Log.i("mss","jsonObject1.getInt(\"status\")"+String.valueOf(jsonObject1.getInt("status"))); }catch(JSONException b) { intent1.putExtra("registerstate","new JSONArray(re);失敗"); } } catch(IOException r) { intent1.putExtra("registerstate","HttpURLConnection IOException失敗"); } catch(NullPointerException r){ intent1.putExtra("registerstate","HttpURLConnection NullPointerException!\n請連線網路後再註冊"); } //返回結果 //已經註冊過 //註冊成功 //註冊失敗,請換一個 //intent1.putExtra("registerstate","註冊成功"+result+" "+re+"<"+String.valueOf(y)+" "+String.valueOf(l)); sendBroadcast(intent1);