连接网络,使用 httpClient 的一般使用步骤:
- 使用DefaultHttpClient类实例化HttpClient对象
- 创建HttpGet或HttpPost对象,将要请求的URL通过构造方法传入HttpGet或HttpPost对象
- 调用execute方法发送HTTP GET 或HTTP POST请求,并返回HttpResponse对象
- 通过HttpResponse接口的getEntity方法返回响应信息,并进行相应处理
实例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
| public class NetUtils {
private static final String TAG = "NetUtils";
public static String loginOfPost(String userName, String password) { HttpClient client = null; try { client = new DefaultHttpClient(); HttpPost post = new HttpPost("http://10.0.2.2:8080/ServerItheima28/servlet/LoginServlet"); List<NameValuePair> parameters = new ArrayList<NameValuePair>(); parameters.add(new BasicNameValuePair("username", userName)); parameters.add(new BasicNameValuePair("password", password)); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "utf-8"); post.setEntity(entity);
HttpResponse response = client.execute(post); int statusCode = response.getStatusLine().getStatusCode(); if(statusCode == 200) { InputStream is = response.getEntity().getContent(); String text = getStringFromInputStream(is); return text; } else { Log.i(TAG, "请求失败: " + statusCode); } } catch (Exception e) { e.printStackTrace(); } finally { if(client != null) { client.getConnectionManager().shutdown(); } } return null; }
public static String loginOfGet(String userName, String password) { HttpClient client = null; try { client = new DefaultHttpClient(); String data = "username=" + userName + "&password=" + password; HttpGet get = new HttpGet("http://10.0.2.2:8080/ServerItheima28/servlet/LoginServlet?" + data); HttpResponse response = client.execute(get); int statusCode = response.getStatusLine().getStatusCode(); if(statusCode == 200) { InputStream is = response.getEntity().getContent(); String text = getStringFromInputStream(is); return text; } else { Log.i(TAG, "请求失败: " + statusCode); } } catch (Exception e) { e.printStackTrace(); } finally { if(client != null) { client.getConnectionManager().shutdown(); } } return null; }
private static String getStringFromInputStream(InputStream is) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = -1; while((len = is.read(buffer)) != -1) { baos.write(buffer, 0, len); } is.close(); String html = baos.toString();
baos.close(); return html; } }
|