httpclient4.3 访问外部url使用方法实例
httpclient4.3.3官方下载地址如下
http://hc.apache.org/downloads.cgi
httpcomponents-client-4.3.3-bin.zip
下载后把lib下面的jar放到工程项目的lib目录下
commons-codec-1.6.jar
commons-logging-1.1.3.jar
fluent-hc-4.3.3.jar
httpclient-4.3.3.jar
httpclient-cache-4.3.3.jar
httpcore-4.3.2.jar
httpmime-4.3.3.jar
httpclient4.3访问url代码如下:
使用get请求方式和post请求方式
import java.net.URI; import org.apache.http.HttpEntity; import org.apache.http.HttpStatus; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URIBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class HttpclientTest { public static void main(String[] args) { CloseableHttpClient httpclient = HttpClients.createDefault(); try { URI uri = new URIBuilder() .setScheme("http") .setHost("www.baidu.com") .setPath("/index.php") .addParameter("id", "1") .build(); //get 请求方式 HttpGet httpget = new HttpGet(uri); CloseableHttpResponse response =httpclient.execute(httpget); //post 请求方式 //HttpPost httpPost = new HttpPost(uri); //CloseableHttpResponse response =httpclient.execute(httpPost); System.out.println(response.getStatusLine()); String content; if( response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ HttpEntity entity = response.getEntity(); content = EntityUtils.toString(entity); System.out.println(content); } } catch (Exception e) { System.out.println(e); } } }
来源://作者:/更新时间:2014-04-24
顶
踩
相关文章: