Get方式访问
HttpClient hc = new DefaultHttpClient(); HttpUriRequest request = new HttpGet("http://www.baidu.com?wd=HttpClient"); HttpResponse hr = hc.execute(request); String body = EntityUtils.toString(hr.getEntity()); System.out.println(body);
Post方式访问
DefaultHttpClient hc = new DefaultHttpClient(); hc.setRedirectStrategy(new LaxRedirectStrategy()); //如果有跳转,就返回跳转后的内容 HttpPost hp = new HttpPost("http://www.baidu.com?wd=HttpClient"); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("username", "angelshelter")); params.add(new BasicNameValuePair("keyword", "123")); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8"); hp.setEntity(entity); HttpResponse hr = hc.execute(hp); String body = EntityUtils.toString(hr.getEntity()); System.out.println(body);
Proxy代理访问。
public class Main { public static void main(String[] args) { List<Thread> list = new ArrayList<Thread>(); for(int i=0;i<3;i++){ Thread thread = new Thread(new Runnable(){ @Override public void run() { try{ HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost("http://wxgd.online.atianqi.com:8010/wxgdol/getobjdetail"); //HttpHost proxy = new HttpHost("localhost", 8888); //RequestConfig config = RequestConfig.custom().setProxy(proxy).build(); //post.setConfig(config); //HttpHost proxy = new HttpHost("localhost", 8888); //client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy); //post.setHeader("Content-Type", "application/json;charset=UTF-8"); StringEntity entity = new StringEntity("{"reqhead":{"servicecode":"OTTTV","distributor":"SNM","clienttype":"PC","clientid":"JHSG7328f","clientver":"1.0.1","devicetype":"","clientos":"andiod_4.3.1"},"reqbody":{"objectid":"news_1469974","parentcode":"x_wx_yj_zy_bd_news"}}", "utf-8"); post.setEntity(entity); //使用代理 HttpResponse res = client.execute(post); System.out.println("#" + EntityUtils.toString(res.getEntity()) + "#"); }catch(Exception e){ e.printStackTrace(); } } }); list.add(thread); } for(Thread t : list){ t.start(); } } }