封装get/post方法
public class RestfulClient {
private CloseableHttpClient httpclient;
private HttpGet httpGet;
private HttpPost httpPost;
private CloseableHttpResponse httpResponse;
private int responseCode;
private JSONObject responseBody;
private HashMap<String, String> responseHeads;
public void getResponse(String url) throws ClientProtocolException, IOException{
httpclient = HttpClients.createDefault();
httpGet = new HttpGet(url);
httpResponse = httpclient.execute(httpGet);
}
public void sendPost(String url, List<NameValuePair> params, HashMap<String, String> headers) throws ClientProtocolException, IOException{
httpclient = HttpClients.createDefault();
httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
Set<String> set = headers.keySet();
for(Iterator<String> iterator = set.iterator(); iterator.hasNext();){
String key = iterator.next();
String value = headers.get(key);
httpPost.addHeader(key, value);
}
httpResponse = httpclient.execute(httpPost);
}
public void sendPost(String url, List<NameValuePair> params) throws ClientProtocolException, IOException{
httpclient = HttpClients.createDefault();
httpPost = new HttpPost(url);
HashMap<String, String> headers = new HashMap<String, String>();
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
Set<String> set = headers.keySet();
for(Iterator<String> iterator = set.iterator(); iterator.hasNext();){
String key = iterator.next();
String value = headers.get(key);
httpPost.addHeader(key, value);
}
httpResponse = httpclient.execute(httpPost);
}
public void sendPost(String url) throws ClientProtocolException, IOException{
httpclient = HttpClients.createDefault();
httpPost = new HttpPost(url);
HashMap<String, String> headers = new HashMap<String, String>();
List<NameValuePair> params =new ArrayList<NameValuePair>();
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
Set<String> set = headers.keySet();
for(Iterator<String> iterator = set.iterator(); iterator.hasNext();){
String key = iterator.next();
String value = headers.get(key);
httpPost.addHeader(key, value);
}
httpResponse = httpclient.execute(httpPost);
}
public JSONObject getBodyInJSON() throws ParseException, IOException{
HttpEntity entity;
String entityToString;
entity = httpResponse.getEntity();
entityToString = EntityUtils.toString(entity);
responseBody = JSON.parseObject(entityToString);
System.out.println("This is your response body " + responseBody);
return responseBody;
}
public HashMap<String, String> getHeaderInHash(){
Header[] headers;
headers = httpResponse.getAllHeaders();
responseHeads = new HashMap<String, String>();
for(Header header:headers){
responseHeads.put(header.getName(), header.getValue());
}
System.out.println("This is your response header " + responseHeads);
return responseHeads;
}
public int getCodeInNumber(){
responseCode = httpResponse.getStatusLine().getStatusCode();
System.out.println("This is your response code " + responseCode);
return responseCode;
}
}