依赖:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.5</version>
</dependency>
代码:
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import sun.net.www.http.HttpClient;
import javax.swing.text.html.parser.Entity;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class HttpRequestUtil {
public static void main(String args[]){
try {
sendPostRequest("http://localhost:8090/auth/signIn");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 发送get请求
* @param url
* @throws IOException
*/
public static void sendGetRequest(String url) throws IOException{
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse closeableHttpResponse=httpClient.execute(httpGet);
int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
if(statusCode==200){
HttpEntity entity = closeableHttpResponse.getEntity();
System.out.println("请求成功");
System.out.println(EntityUtils.toString(entity,"utf-8"));
}
}
/**
* 发送post请求
* @param url
* @throws IOException
*/
public static void sendPostRequest(String url) throws IOException{
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> params = new ArrayList<NameValuePair>();
httpPost.setHeader("token", "644064"); //设置头部信息
params.add(new BasicNameValuePair("username","000000")); //设置参数
params.add(new BasicNameValuePair("password","000000"));
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(params, "UTF-8");
httpPost.setEntity(urlEncodedFormEntity);
CloseableHttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) { //返回状态码,并打印返回信息
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, "UTF-8");
System.out.println("result:" + result);
}
}
}