public class HttpUtils {
public static String getJson(String url){
//1、创建请求方式对象
HttpGet get=new HttpGet(url);
//2、创建客户端对象
HttpClient client= HttpClientBuilder.create().build();
try {
//3、获取请求结果
HttpResponse response=client.execute(get);
//4、校验http状态码
if(response.getStatusLine().getStatusCode()==200){
//获取响应的内容对象
HttpEntity entity=response.getEntity();
//转换结果位字符串
return EntityUtils.toString(entity);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//请求示例
public static void main(String[] args) throws IOException {
String result = getJson("https://way.jd.com/jisuapi/weather?city=%E5%B9%BF%E5%B7%9E&appkey=9878b9b510123e52a951fe2074d");
System.out.println("getJson method: "+result);
}
}
public class HttpUtils {
/**
* post 传递键值对参数 */
public static String postJson(String url, Map<String,String> map){
//1、创建请求方式对象
HttpPost post=new HttpPost(url);
//2、创建客户端对象
HttpClient client= HttpClientBuilder.create().build();
try {
//3、设置post请求的参数
List<NameValuePair> pairList=new ArrayList<>();
for(String key:map.keySet()){
pairList.add(new BasicNameValuePair(key,map.get(key)));
}
HttpEntity httpEntity=new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8"));
post.setEntity(httpEntity);
//4、获取请求结果
HttpResponse response=client.execute(post);
//5、校验http状态码
if(response.getStatusLine().getStatusCode()==200){
//6、获取响应的内容对象
HttpEntity entity=response.getEntity();
//7、转换结果位字符串
return EntityUtils.toString(entity);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//请求示例
public static void main(String[] args) throws IOException {
HashMap<String, String> paramMap = new HashMap<>();
paramMap.put("city","广州");
paramMap.put("appkey","9878b9b510123e52a951fe2074d19be1");
String result2 = postJson("https://way.jd.com/jisuapi/weather", paramMap);
System.out.println("key value pair param:"+result2);
}
}
public class HttpUtils {
//post request with json parameter
public static String postJson(String url,String paramJson) throws IOException {
//create post request object
HttpPost httpPost = new HttpPost(url);
//create client object
HttpClient httpClient = HttpClientBuilder.create().build();
//setting the request param type
StringEntity stringEntity = new StringEntity(paramJson, ContentType.APPLICATION_JSON);
httpPost.setEntity(stringEntity);
//executes the request and obtains the response
HttpResponse response = httpClient.execute(httpPost);
//check the status code
if (response.getStatusLine().getStatusCode() == 200) {
//obtains the message of response
HttpEntity entity = response.getEntity();
//transfer from entity to String
String result = EntityUtils.toString(entity);
return result;
}
return null;
}
//请求示例
public static void main(String[] args) throws IOException {
HashMap<String, String> paramMap = new HashMap<>();
paramMap.put("city","广州");
paramMap.put("appkey","9878b9b510123e52a951fe2074d19be1");
String result2 = postJson("https://way.jd.com/jisuapi/weather", paramMap.toString());
System.out.println("json param:"+result2);
}
}