2017-07-08 8 views
0

私は、&の電子メールアドレスを受け入れるようにサーバを設定しており、私のアプリはHttpURLconnectionを使ってログインするようにします。応答はいつも200ですが、実際にデータを送信するのに問題があります。 jsonのペアを文字列に変換し、DataOutputStreamを介して送信します。私はInputStreamを通してその応答を読んだ。httpulrconnectionを使用したウェブサイトへのログイン

私の主な問題は、私はのInputStreamを読ん応答は、電子メール&パスワードは私が私が正しくデータを送信していないよ考えていた、間違っている場合でも同じ(ログインページのHTML)は常にされています。あなたは私のコードを見てみることができます

import android.content.Context; 
import android.content.SharedPreferences; 
import android.os.AsyncTask; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.util.JsonWriter; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 
import android.app.ProgressDialog; 
import java.io.DataOutputStream; 
import java.net.MalformedURLException; 
import android.net.Uri; 
import android.widget.Toast; 
import java.io.BufferedReader; 
import java.io.BufferedWriter; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import android.content.Intent; 
import org.json.JSONObject; 
import org.json.JSONStringer; 
import java.io.BufferedOutputStream; 
import java.io.IOException; 
import java.io.OutputStream; 
import java.io.OutputStreamWriter; 
import java.net.HttpURLConnection; 
import java.net.URL; 

public class MainActivity extends AppCompatActivity { 

private EditText user; 
private EditText pswrd; 
private Button login; 
private String email; 
private String password; 
private String HOST; 
private String DEFAULT_IPADDRESS; 
private String PREFERENCES_IPADDRESSSERVER; 
private String PREFERENCES_TOKEN; 
private Context ctx; 
public static final int CONNECTION_TIMEOUT = 10000; 
public static final int READ_TIMEOUT = 15000; 
private String sRequest; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 


    user = (EditText) findViewById(R.id.Email); 
    pswrd = (EditText) findViewById(R.id.Password); 
    login = (Button) findViewById(R.id.button); 



    login.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      email = user.getText().toString(); 
      password = pswrd.getText().toString(); 
      try { 
       //HttpURLConnection example = serverLogin(email, password); 
       new AsyncLogin().execute(email, password); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 


     } 
    }); 


} 

private class AsyncLogin extends AsyncTask<String, String, String> { 
    ProgressDialog pdLoading = new ProgressDialog(MainActivity.this); 
    HttpURLConnection conn; 
    URL url = null; 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 

     //this method will be running on UI thread 
     pdLoading.setMessage("\tLoading..."); 
     pdLoading.setCancelable(false); 
     pdLoading.show(); 

    } 

    @Override 
    protected String doInBackground(String... params) { 
     try { 

      // Enter URL address 
      url = new URL("http://81.169.151.83/users/sign_in"); 

     } catch (MalformedURLException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
      return "exception"; 
     } 
     try { 
      // Setup HttpURLConnection class to send and receive data 
      conn = (HttpURLConnection) url.openConnection(); 
      conn.setReadTimeout(READ_TIMEOUT); 
      conn.setConnectTimeout(CONNECTION_TIMEOUT); 
      conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); 
      conn.setRequestMethod("POST"); 

      // setDoInput and setDoOutput method depict handling of both send and receive 
      conn.setDoInput(true); 
      conn.setDoOutput(true); 

      JSONObject request = new JSONObject(); 
      try { 
       request.put("email", params[0]); 
       request.put("password", params[1]); 

      } catch (org.json.JSONException e) { 
       e.printStackTrace(); 
      } 
      sRequest = request.toString(); 




      // Open connection for sending data 
      conn.connect(); 
      DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); 
      wr.writeBytes(sRequest); 
      wr.flush(); 
      wr.close(); 


     } catch (IOException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
      return "exception"; 
     } 

     try { 

      int response_code = conn.getResponseCode(); 

      // Check if successful connection made 
      if (response_code == HttpURLConnection.HTTP_OK) { 


       // Read data sent from server 
       InputStream input = conn.getInputStream(); 
       BufferedReader reader = new BufferedReader(new InputStreamReader(input)); 
       StringBuilder result = new StringBuilder(); 
       String line; 

       while ((line = reader.readLine()) != null) { 
        result.append(line); 
       } 

       // Pass data to onPostExecute method 
       return (result.toString()); 

      } else { 

       return ("unsuccessful"); 
      } 

     } catch (IOException e) { 
      e.printStackTrace(); 
      return "exception"; 
     } finally { 
      conn.disconnect(); 
     } 


    } 

    @Override 
    protected void onPostExecute(String result) { 

     //this method will be running on UI thread 

     pdLoading.dismiss(); 

     if (result.equalsIgnoreCase("true")) { 
      /* Here launching another activity when login successful. If you persist login state 
      use sharedPreferences of Android. and logout button to clear sharedPreferences. 
      */ 
      Toast.makeText(MainActivity.this, "GREAT SUCCESS", Toast.LENGTH_LONG).show(); 
     /* Intent intent = new Intent(MainActivity.this,SuccessActivity.class); 
      startActivity(intent); 
      MainActivity.this.finish();*/ 

     } else if (result.equalsIgnoreCase("false")) { 

      // If username and password does not match display a error message 
      Toast.makeText(MainActivity.this, "Invalid email or password", Toast.LENGTH_LONG).show(); 

     } else if (result.equalsIgnoreCase("exception") || result.equalsIgnoreCase("unsuccessful")) { 

      Toast.makeText(MainActivity.this, "OOPs! Something went wrong. Connection Problem.", Toast.LENGTH_LONG).show(); 

     } 
    } 

} 

おかげ

答えて

0

私は彼らのrecipesをチェックアウトし、OKHTTPをしようとするあなたをお勧めします、でGET/POSTリクエストを行うにはずっと簡単ですアンドロイド。

あなたのウェブサイトはhttp://81.169.151.83/users/sign_inでチェックアウトされており、ログインフォームに使用されるパラメータはuser [email]とuser [password]です。上記で追加した電子メールとパスワードではありません。また、原因かもしれないauthenticity_tokenのようないくつかの他のフォームフィールドがあります。

+0

こんにちは、お返事ありがとうございます。私はOKHTTPを調べ始めるでしょう。また、私は正しくparams文字列を構築していませんか? –

+0

私はそうは思わない。ブラウザの開発者ツールを使用して、POSTログイン要求を行い、送信されたパラメータを確認することができます。また、ログインフォームのフォームフィールドを見ることもできます。 – licitdev

+0

Chromeの開発ツールでは、ユーザー[電子メール]とユーザー[パスワード]の両方が少なくとも自分の資格情報と一致します。コードを電子メールとパスワードからユーザー[]のペアに変更すると、401が返されます。これはトークンのためでしょうか?これについていくつか指摘していただけますか? –

関連する問題