HttpClient4使用
package main; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.ParseException; 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.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; public classMain { private static HttpClient hc =newDefaultHttpClient(); /** * @param args */ public static void main(String[] args) { List params =newArrayList(); params.add(new BasicNameValuePair("email","xxx@gmail.com")); params.add(new BasicNameValuePair("pwd","xxx")); params.add(new BasicNameValuePair("save_login","1")); String url ="http://www.oschina.net/action/user/login"; String body = post(url, params); System.out.println(body); } /** * Get請求 * @param url * @param params * @return */ public static String get(String url, List params) { String body =null; try{ // Get請求 HttpGet httpget =newHttpGet(url); // 設(shè)置參數(shù) String str = EntityUtils.toString(newUrlEncodedFormEntity(params)); httpget.setURI(newURI(httpget.getURI().toString() +"?"+ str)); // 發(fā)送請求 HttpResponse httpresponse = hc.execute(httpget); // 獲取返回數(shù)據(jù) HttpEntity entity = httpresponse.getEntity(); body = EntityUtils.toString(entity); if(entity !=null) { entity.consumeContent(); } }catch(ParseException e) { e.printStackTrace(); }catch(UnsupportedEncodingException e) { e.printStackTrace(); }catch(IOException e) { e.printStackTrace(); }catch(URISyntaxException e) { e.printStackTrace(); } return body; } /** * // Post請求 * @param url * @param params * @return */ public static String post(String url, List params) { String body =null; try{ // Post請求 HttpPost httppost =newHttpPost(url); // 設(shè)置參數(shù) httppost.setEntity(newUrlEncodedFormEntity(params)); // 發(fā)送請求 HttpResponse httpresponse = hc.execute(httppost); // 獲取返回數(shù)據(jù) HttpEntity entity = httpresponse.getEntity(); body = EntityUtils.toString(entity); if(entity !=null) { entity.consumeContent(); } }catch(Unsuppor