2017-02-13 7 views
0

アンドロイドアプリからサーバーに名前と姓を送信しようとしています。しかし、接続を得ることができません。利用可能なコードのほとんどは使用していますが、いずれも作業していません。以下は私のコードのスナップショットです:アンドロイドアプリからサーバーへのHttpリクエスト

private void nextActivity(Profile profile) { 
    HttpURLConnection con = null; 

    try { 
     con = (HttpURLConnection)(new URL("**********/index.php")).openConnection();//not written the url for privacy concern 
     con.setRequestMethod("POST"); 
     con.setDoInput(true); 
     con.setDoOutput(true); 
     con.connect(); 
     con.getOutputStream().write(("name=" + profile.getFirstName()).getBytes()); 
     con.getOutputStream().write(("surname=" + profile.getLastName()).getBytes()); 
    } 
    catch (ProtocolException e) { 
     e.printStackTrace(); 
    } 
    catch (IOException e) { 
     e.printStackTrace(); 
    } 

    if (profile != null) { 
     Intent main = new Intent(LoginActivity.this, MainActivity.class); 
     main.putExtra("name", profile.getFirstName()); 
     main.putExtra("surname", profile.getLastName()); 
     main.putExtra("imageUrl", profile.getProfilePictureUri(200, 200).toString()); 
     startActivity(main); 
    } 
} 
} 
+1

私はあなたがここに...インターネット許可の –

+1

チェックをAsyncTaskを使用している願っています&サーバー – VVB

+0

あなたが例外を取得んpingを実行してみてください? –

答えて

0

このコードをAsyncTaskとして使用し、問題を解決しました。

class MyAsyncTask extends AsyncTask<String, Void, String> { 

    @Override 
    protected String doInBackground(String... params) { 
     try { 
      String id = params[0], firstname = params[1], lastname = params[2]; 

      URL url = new URL("http://*******index.php"); 


      HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); 
      httpURLConnection.setRequestMethod("POST"); 
      httpURLConnection.setDoOutput(true); 

      OutputStream OS = httpURLConnection.getOutputStream(); 
      BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8")); 
      String data = URLEncoder.encode("id", "UTF-8") + "=" + URLEncoder.encode(id, "UTF-8") + 
        "&" + URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(firstname, "UTF-8") + "&" 
        + URLEncoder.encode("surname", "UTF-8") + "=" + URLEncoder.encode(lastname, "UTF-8"); 
      bufferedWriter.write(data); 
      bufferedWriter.flush(); 
      bufferedWriter.close(); 
      OS.close(); 
      InputStream IS = httpURLConnection.getInputStream(); 
      IS.close(); 

     } catch (MalformedURLException e) { 
      // ... 
     } catch (IOException e) { 
      // ... 
     } 
     return null; 
    } 
} 
0

あなたのコードにこれらの行を追加してみてください。

con.getOutputStream().flush(); 
con.getOutputStream().close(); 
+0

が機能しません。アプリはすでに –

0

まず、URLエンコーダを使用してデータをエンコードし、出力ストリームで書き込みます。

+0

がクラッシュし始めました。しかし、動作していません –

+0

あなたが得ているエラーを共有してください。 –

関連する問題