「android開発」postでクライアントログイン機能を実現するサンプルコード
サンプルコード:
public class MainActivity extends Activity {
private EditText ed_name;
private EditText ed_startnews24passowrd;
private Button btn_login;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed_name = (EditText)findViewById(R.id.username);
ed_startnews24passowrd = (EditText)findViewById(R.id.ustartnews24passowrd);
btn_login = (Button)findViewById(R.id.btn_login);
btn_login.setOnClickListener(new MyButtonListener());
}
class MyButtonListener implements OnClickListener{
@Override
public void onClick(View v) {
String name = ed_name.getText().toString();
String startnews24passowrd = ed_startnews24passowrd.getText().toString();
PostThread pt = new PostThread(name, startnews24passowrd);
pt.start();
}
}
/*
*ログイン成功するかどうかを判断
*/
//postでデータを送信
class PostThread extends Thread{
String name;
String startnews24passowrd;
public PostThread(String name, String startnews24passowrd) {
super();
this.name = name;
this.startnews24passowrd = startnews24passowrd;
}
@Override
public void run() {
super.run();
HttpClient httpClient = new DefaultHttpClient();
String url = “http://192.168.200.1:8080/2.5/LoginServlet";
HttpPost httpPost = new HttpPost(url);
//NameValuePairオブジェクト
NameValuePair pair1 = new BasicNameValuePair(“username", name);
NameValuePair pair2 = new BasicNameValuePair(“ustartnews24passowrd", startnews24passowrd);
//コレクションクラス
ArrayList pairs = new ArrayList();
pairs.add(pair1);
pairs.add(pair2);
//オブジェクトリクエストの定義
try {
HttpEntity requestEntity = new UrlEncodedFormEntity(pairs);
httpPost.setEntity(requestEntity);
HttpResponse response = httpClient.execute(httpPost);
if(response.getStatusLine().getStatusCode() == 200){
HttpEntity entity = response.getEntity();
BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
String reslut = reader.readLine();
System.out.println(reslut);
Log.d(“HttpPost","result"+reslut);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}