框架
okhttp
String url = "http://www.lemonban.com/";
final OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.get()
.build();
Response response = client.newCall(request).execute();
System.out.println(response.code());
System.out.println(response.headers());
System.out.println(response.body().string());
String url = "http://www.lemonban.com/";
final OkHttpClient client = new OkHttpClient();
MediaType type = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body=RequestBody.create(type,"username=123434545&password=121324");
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
System.out.println(response.code());
System.out.println(response.headers());
System.out.println(response.body().string());
httpclient
public void testGet() throws Exception{
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://localhost:8080/user/shop/status");
CloseableHttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
System.out.println(statusCode);
HttpEntity entity = response.getEntity();
String body = EntityUtils.toString(entity);
System.out.println("服务端返回的数据为:" + body);
response.close();
httpClient.close();
}
public void testPost() throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://localhost:8080/admin/employee/login");
JSONObject jsonObject = new JSONObject();
jsonObject.put("username","admin");
jsonObject.put("password","123456");
StringEntity entity = new StringEntity(jsonObject.toString());
entity.setContentEncoding("utf-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
CloseableHttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
System.out.println(statusCode);
HttpEntity entity1 = response.getEntity();
String body = EntityUtils.toString(entity1);
System.out.println("响应数据为:" + body);
response.close();
httpClient.close();
}