使用HttpClient-4.5.3发送POST和GET请求
使用HttpClient4.5.3的jar包,对post、get、delete、put请求进行了封装,我是用于服务器集成环信REST接口的,希望对大家有帮助:
package CAM.sys.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
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 net.sf.json.JSONObject;
public class HttpClientUtil {
public static JSONObject Delete(String url, JSONObject jsonParam, String... tokens) {
CloseableHttpClient httpclient = HttpClients.createDefault();
JSONObject js = null;
url = buildGetUrl(url, jsonParam);
System.out.println("getURL====>" + url);
try {
HttpDelete httpDelete = new HttpDelete(url);
if (tokens != null && tokens[0] != null && tokens.length == 1) {
httpDelete.addHeader("Authorization", "Bearer " + tokens[0]);
}
CloseableHttpResponse response1 = httpclient.execute(httpDelete);
try {
System.out.println(response1.getStatusLine());
HttpEntity entity1 = response1.getEntity();
if (entity1 != null) {
try {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(entity1.getContent(), "UTF-8"), 8 * 1024);
StringBuilder entityStringBuilder = new StringBuilder();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
entityStringBuilder.append(line);
}
js = JSONObject.fromObject(entityStringBuilder.toString());
System.out.println("Delte 返回数据:" + entityStringBuilder.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
EntityUtils.consume(entity1);
} catch (IOException e) {
e.printStackTrace();
} finally {
response1.close();
}
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return js;
}
public static JSONObject Put(String url, JSONObject jsonParam, String... tokens) {
JSONObject js = null;
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPut httpPut = new HttpPut(url);
if (tokens != null && tokens.length == 1) {
httpPut.addHeader("Authorization", "Bearer " + tokens[0]);
}
StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPut.setEntity(entity);
CloseableHttpResponse response2 = httpclient.execute(httpPut);
try {
System.out.println("返回状态:" + response2.getStatusLine());
HttpEntity entity2 = response2.getEntity();
if (entity2 != null) {
try {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(entity2.getContent(), "UTF-8"), 8 * 1024);
StringBuilder entityStringBuilder = new StringBuilder();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
entityStringBuilder.append(line);
}
System.out.println("Put 返回数据:" + entityStringBuilder.toString());
js = JSONObject.fromObject(entityStringBuilder.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
EntityUtils.consume(entity2);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
response2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return js;
}
public static JSONObject Get(String url, JSONObject jsonParam, String... tokens) {
CloseableHttpClient httpclient = HttpClients.createDefault();
JSONObject js = null;
url = buildGetUrl(url, jsonParam);
System.out.println("getURL====>" + url);
try {
HttpGet httpGet = new HttpGet(url);
if (tokens != null && tokens[0] != null && tokens.length == 1) {
httpGet.addHeader("Authorization", "Bearer " + tokens[0]);
}
CloseableHttpResponse response1 = httpclient.execute(httpGet);
try {
System.out.println(response1.getStatusLine());
HttpEntity entity1 = response1.getEntity();
if (entity1 != null) {
try {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(entity1.getContent(), "UTF-8"), 8 * 1024);
StringBuilder entityStringBuilder = new StringBuilder();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
entityStringBuilder.append(line);
}
js = JSONObject.fromObject(entityStringBuilder.toString());
System.out.println("Get 返回数据:" + entityStringBuilder.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
EntityUtils.consume(entity1);
} catch (IOException e) {
e.printStackTrace();
} finally {
response1.close();
}
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return js;
}
public static JSONObject Post(String url, JSONObject jsonParam, String... tokens) {
JSONObject js = null;
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httpPost = new HttpPost(url);
if (tokens != null && tokens.length == 1) {
httpPost.addHeader("Authorization", "Bearer " + tokens[0]);
}
StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
CloseableHttpResponse response2 = httpclient.execute(httpPost);
try {
System.out.println("返回状态:" + response2.getStatusLine());
HttpEntity entity2 = response2.getEntity();
if (entity2 != null) {
try {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(entity2.getContent(), "UTF-8"), 8 * 1024);
StringBuilder entityStringBuilder = new StringBuilder();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
entityStringBuilder.append(line);
}
System.out.println("post 返回数据:"+entityStringBuilder.toString());
js = JSONObject.fromObject(entityStringBuilder.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
EntityUtils.consume(entity2);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
response2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return js;
}
private static String buildGetUrl(String url, JSONObject jsonParam) {
Map<String, String> map = new HashMap<String, String>();
Iterator<?> it = jsonParam.keys();
while (it.hasNext()) {
String key = (String) it.next();
String value = jsonParam.getString(key);
map.put(key, value);
}
StringBuffer uriStr = new StringBuffer(url);
if (map != null && !map.isEmpty()) {
List<NameValuePair> ps = new ArrayList<NameValuePair>();
for (String key : map.keySet()) {
ps.add(new BasicNameValuePair(key, map.get(key)));
}
uriStr.append("?");
uriStr.append(URLEncodedUtils.format(ps, Charset.forName("UTF-8")));
}
return uriStr.toString();
}
public static String getToken() {
String token = "";
String url = "你的URL";
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httpPost = new HttpPost(url);
JSONObject jsonParam = new JSONObject();
jsonParam.accumulate("grant_type", "client_credentials");
jsonParam.accumulate("client_id", "你的client_id");
jsonParam.accumulate("client_secret", "你的client_secret");
StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
CloseableHttpResponse response2 = httpclient.execute(httpPost);
try {
System.out.println("返回状态:" + response2.getStatusLine());
HttpEntity entity2 = response2.getEntity();
if (entity2 != null) {
try {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(entity2.getContent(), "UTF-8"), 8 * 1024);
StringBuilder entityStringBuilder = new StringBuilder();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
entityStringBuilder.append(line);
}
System.out.println("getToken 返回数据:" + entityStringBuilder.toString());
token = JSONObject.fromObject(entityStringBuilder.toString()).get("access_token").toString();
} catch (Exception e) {
e.printStackTrace();
}
}
EntityUtils.consume(entity2);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
response2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return token;
}
public static void main(String[] args) throws ClientProtocolException, IOException {
String token = HttpClientUtil.getToken();
JSONObject jsonParam = new JSONObject();
String url = "你的URL";
jsonParam.accumulate("nickname", "88888");
System.out.println(Put(url,jsonParam,token));
}
}