0.HttpClient
作用:执行Http请求的类,可以处理Cookie,身份验证,链接管理和其他。。
public HttpClient getHttpClient() {
// 创建 HttpParams 以用来设置 HTTP 参数(这一部分不是必需的) this.httpParams = new BasicHttpParams(); // 设置连接超时和 Socket 超时,以及 Socket 缓存大小 HttpConnectionParams.setConnectionTimeout(httpParams, 20 * 1000); HttpConnectionParams.setSoTimeout(httpParams, 20 * 1000); HttpConnectionParams.setSocketBufferSize(httpParams, 8192); // 设置重定向,缺省为 true HttpClientParams.setRedirecting(httpParams, true); // 设置 user agent String userAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2) Gecko/20100115 Firefox/3.6"; HttpProtocolParams.setUserAgent(httpParams, userAgent); // 创建一个 HttpClient 实例 // 注意 HttpClient httpClient = new HttpClient(); 是Commons HttpClient // 中的用法,在 Android 1.5 中我们需要使用 Apache 的缺省实现 DefaultHttpClient httpClient = new DefaultHttpClient(httpParams); return httpClient; }
1.Get
StringBuffer path = new StringBuffer("www.baidu.com"); path.append("?"); path.append("name=zhangshan"); try { path.append("password=" + URLEncoder.encode("1234", "")); HttpGet httpGet = new HttpGet(path.toString()); HttpResponse reponse = new DefaultHttpClient().execute(httpGet); if (reponse.getStatusLine().getStatusCode() == 200) { String result = EntityUtils.toString(reponse.getEntity()); String str = new String(result.getBytes("ISO_8859_1"), "utf-8"); System.out.println(str); //return str; } } 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(); }
2. Post
String url = " http://192.168.0.131:8888/kon_service/AddQuestionServlet"; HttpClient client = new DefaultHttpClient(); HttpParams httpParams = client.getParams(); //设置网络超时参数 HttpConnectionParams.setConnectionTimeout(httpParams, 3000); HttpConnectionParams.setSoTimeout(httpParams, 5000); HttpPost request = new HttpPost(url); //设置HTTP POST请求参数必须用NameValuePair List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("title", "")); params.add(new BasicNameValuePair("content","")); params.add(new BasicNameValuePair("resolve","")); params.add(new BasicNameValuePair("u_id","")); try{ //设置Http Post请求参数 request.setEntity( new UrlEncodedFormEntity(params,HTTP.UTF_8)); HttpResponse response = new DefaultHttpClient().execute(request); if(response.getStatusLine().getStatusCode()==200){ String msg = EntityUtils.toString(response.getEntity()); Toast.makeText(this, msg, Toast.LENGTH_LONG).show(); Intent i = new Intent(this,TopActivity.class); startActivity(i); } }catch(Exception e){ e.printStackTrace(); }