1、首先要在eclipse中导入HttpClient的jar包。
2、新建类并写入一下代码:
package com.day2.sample;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
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;
//导包带有httpclient的,按ctrl+shift+o
public class HttpClientDemo {
//构造一个get类型的请求,发给服务器
public void test_get() throws URISyntaxException, ClientProtocolException, IOException{
//1.新建一个客户端对象
CloseableHttpClient client=HttpClients.createDefault();
//2.使用URIBuilder来生成一个get类型的URI
URI uri = new URIBuilder()
.setScheme("http") //设置协议
.setPort(8080)
.setHost("localhost")
.setPath("/test1312/Calc")
.setParameter("a", "1")
.setParameter("b", "2")
.build(); //把set设置的值按照get接口类型进行拼接
//3.新建一个HttpGet类型的get请求对象,并使用uri进行初始化->
//将uri请求值赋给get对象
HttpGet get = new HttpGet(uri);
//4.新建一个响应对象来接收客户端执行get的结果
CloseableHttpResponse response = client.execute(get);
//5.从响应对象中提取需要的结果-->实际结果,与预期结果进行对比
if(response.getStatusLine().getStatusCode() == 200){
System.out.println(EntityUtils.toString(response.getEntity()));
}
}
}
3、新建一个类,调用这个类的方法就可以了,类中的参数可以进行参数化设置,或设置成变量,可用有参有返,有参无返更方便进行复用。
package com.day2.sample;
import java.io.IOException; import java.net.URISyntaxException;
import org.apache.http.client.ClientProtocolException;
public class HttpClientTest {
public static void main(String[] args) throws ClientProtocolException, URISyntaxException, IOException {
HttpClientDemo demo = new HttpClientDemo();
demo.test_get();
}
}
//忘多多批评指正:。)