模板文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/tv_user" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="用户名" /> <EditText android:id="@+id/et_user" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="请填写用户名" /> <TextView android:id="@+id/tv_pass" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="密码" /> <EditText android:id="@+id/et_pass" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="请填写密码" /> <Button android:id="@+id/button" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="get登录" android:onClick="getLogin" /> <Button android:id="@+id/button2" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="post登录" android:onClick="postLogin" /> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="httpClientGet登录" android:onClick="clientGetLogin" /> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="httpClientPost登录" android:onClick="clientPostLogin" /> </LinearLayout>
MainActivity
package com.http.action; import com.login.service.LoginService; import android.app.Activity; import android.app.ActionBar; import android.app.Fragment; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import android.os.Build; public class MainActivity extends Activity { protected static final int LOGIN_SUCCESS = 1; protected static final int LOGIN_ERROR = 2; private EditText et_user; private EditText et_pass; private Handler handler = new Handler() { public void handleMessage(android.os.Message message) { switch (message.what) { case LOGIN_SUCCESS: Toast.makeText(MainActivity.this, (String) message.obj, Toast.LENGTH_SHORT).show(); break; case LOGIN_ERROR: Toast.makeText(MainActivity.this, "登录失败", Toast.LENGTH_SHORT).show(); break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); et_user = (EditText) findViewById(R.id.et_user); et_pass = (EditText) findViewById(R.id.et_pass); } /** * 登录 * @param view */ public void getLogin(View view) { final String user = et_user.getText().toString().trim(); final String pass = et_pass.getText().toString().trim(); new Thread(){ public void run() { String res = LoginService.byGetLogin(user, pass); if (res != null) { Message msg = new Message(); msg.what = LOGIN_SUCCESS; msg.obj = res; handler.sendMessage(msg); } else { Message msg = new Message(); msg.what = LOGIN_ERROR; handler.sendMessage(msg); } } }.start(); } /** * post 方式提交 * @param view */ public void postLogin(View view) { final String user = et_user.getText().toString().trim(); final String pass = et_pass.getText().toString().trim(); new Thread(){ public void run() { String text = LoginService.byPostLogin(user, pass); if (text != null) { Message msg = new Message(); msg.what = LOGIN_SUCCESS; msg.obj = text; handler.sendMessage(msg); } else { Message msg = new Message(); msg.what = LOGIN_ERROR; handler.sendMessage(msg); } } }.start(); } /** * client get login * @param view */ public void clientGetLogin(View view) { final String user = et_user.getText().toString().trim(); final String pass = et_pass.getText().toString().trim(); new Thread(){ public void run() { String res = LoginService.httpClientGetLogin(user, pass); if (res != null) { Message msg = new Message(); msg.what = LOGIN_SUCCESS; msg.obj = res; handler.sendMessage(msg); } else { Message msg = new Message(); msg.what = LOGIN_ERROR; handler.sendMessage(msg); } } }.start(); } /** * client post login * @param view */ public void clientPostLogin(View view) { final String user = et_user.getText().toString().trim(); final String pass = et_pass.getText().toString().trim(); new Thread(){ public void run() { String res = LoginService.httpClientPostLogin(user, pass); if (res != null) { Message msg = new Message(); msg.what = LOGIN_SUCCESS; msg.obj = res; handler.sendMessage(msg); } else { Message msg = new Message(); msg.what = LOGIN_ERROR; handler.sendMessage(msg); } } }.start(); } }
LoginService
package com.login.service; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpConnection; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import com.stream.utils.Stream; public class LoginService { /** * 通过get方式提交 * @param user * @param pass * @return */ static public String byGetLogin(String user, String pass) { String path = "http://192.168.0.105/index.php?user="+user+"&pass="+pass; try { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(5000); conn.setRequestMethod("GET"); int code = conn.getResponseCode(); System.out.println(code); if (code == 200) { InputStream is = conn.getInputStream(); String text = Stream.isToString(is); return text; } else { return null; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } /** * 通过post方式提交 * @param user * @param pass * @return */ static public String byPostLogin(String user, String pass) { String path = "http://192.168.0.105/index.php"; try { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); String data = "user="+user+"&pass="+pass; conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", data.length()+""); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); os.write(data.getBytes()); int code = conn.getResponseCode(); if (code == 200) { InputStream is = conn.getInputStream(); return Stream.isToString(is); } else { return null; } } catch (Exception e) { e.printStackTrace(); return null; } } /** * 采用httpclient get 提交 * @param user * @param pass * @return */ static public String httpClientGetLogin(String user, String pass) { String path = "http://192.168.0.105/index.php?user="+user+"&pass="+pass; try { HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(path); HttpResponse response = client.execute(get); int code = response.getStatusLine().getStatusCode(); if (code == 200) { InputStream is = response.getEntity().getContent(); String text = Stream.isToString(is); return text; } return null; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } /** * httpClient post 方式提交 * @param user * @param pass * @return */ static public String httpClientPostLogin(String user, String pass) { String path = "http://192.168.0.105/index.php"; HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(path); List<NameValuePair> parameters = new ArrayList<NameValuePair>(); parameters.add(new BasicNameValuePair("user", user)); parameters.add(new BasicNameValuePair("pass", pass)); try { post.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8")); HttpResponse response = client.execute(post); int code = response.getStatusLine().getStatusCode(); if (code == 200) { InputStream is = response.getEntity().getContent(); String text = Stream.isToString(is); return text; } return null; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } }
stream 把 输入流转换成字符串
package com.stream.utils; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; public class Stream { /** * 把一个输入流变成字符串 * @param is * @return * @throws IOException */ static public String isToString(InputStream is) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); int len = 0; byte[] buffer = new byte[1024]; while ((len = is.read(buffer)) != -1) { baos.write(buffer); } byte[] result = baos.toByteArray(); is.close(); baos.close(); return new String(result); } }
切记清单文件权限
<uses-permission android:name="android.permission.INTERNET"/>
时间: 2024-11-06 09:29:56