1、主代码login:
(1)传递Map参数能具有更好的复用性
import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; public static String sendHttpclientGet(Map<String, String> map, String path, String encode) { // TODO Auto-generated method stub // 填充表单的内容 List<NameValuePair> pairs = new ArrayList<NameValuePair>(); // Key必须与action接收params的key一致 if (map != null && !map.isEmpty()) { // 一个entry代表一个键值对,.getKey()获取键,getValue()获取值 for (Map.Entry<String, String> entry : map.entrySet()) { // 相当于pairs.add(new // BasicNameValuePair("stuid","1109030115")); pairs.add(new BasicNameValuePair(entry.getKey(), entry .getValue())); } } try { // 添加form表单的内容,和网页的jsp一样 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs, encode); // 使用post提交数据 HttpPost httpPost = new HttpPost(path); httpPost.setEntity(entity); HttpClient client = new DefaultHttpClient(); // HttpResponse获得服务器响应的所有消息 HttpResponse response = client.execute(httpPost); // 判断连接成功 if (response.getStatusLine().getStatusCode() == 200) { // HttpEntity获得服务器响应回来的消息体(不包括HTTP HEAD) HttpEntity httpEntity = response.getEntity(); // 自动分辨响应的内容的编码 String defaultCharset = EntityUtils .getContentCharSet(httpEntity); // EntityUtils.toString将获得的消息体转换成String return EntityUtils.toString(httpEntity, defaultCharset); } else { // } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
Done!