导入jar包:
commons-beanutils-1.7.0.jar commons-collections-3.1.jar commons-lang-2.5.jar commons-logging.jar ezmorph-1.0.3.jar json-lib-2.4-jdk15.jar httpclient-4.3.2.jar httpcore-4.3.2.jar
代码:
import java.io.IOException; import java.nio.charset.Charset; import net.sf.json.JSONObject; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; public class AccessRest {
private static AccessRest accessRest = null; private String apiURL = ""; private HttpClient httpClient = null; private HttpPost method = null; / * 默认构造方法 */ private AccessRest() { } / * 含参构造方法 * * @param url */ private AccessRest(String url) { if (null != url && !"".equals(url)) { this.apiURL = url; } if (null != apiURL && !"".equals(apiURL)) { httpClient = new DefaultHttpClient(); method = new HttpPost(apiURL); } } / * 单例方法 * @param url * @return */ public static AccessRest getInstance(String url) { if (accessRest == null) { accessRest = new AccessRest(url); } return accessRest; } / * 设置URL * @param url */ public void setAPIURL(String url){ this.apiURL=url; if (null != apiURL && !"".equals(apiURL)) { httpClient = new DefaultHttpClient(); method = new HttpPost(apiURL); } } / * JSON内容格式的POST请求 * @param params * @return * @throws ClientProtocolException * @throws IOException */ public String JSONToPost(String token,String params) throws ClientProtocolException, IOException { //添加post请求报文header,格式为JSON method.setHeader("Content-type","application/json; charset=utf-8"); method.setHeader("Accept", "application/json"); //添加JSON格式报文内容 method.setEntity(new StringEntity(params, Charset.forName("UTF-8"))); //访问接口 HttpResponse response = httpClient.execute(method); //构造返回值 JSONObject message = new JSONObject(); //添加状态码 message.put("StatusCode", String.valueOf(response.getStatusLine().getStatusCode())); //添加内容 message.put("Message", EntityUtils.toString(response.getEntity())); return message.toString(); } / * 普通参数访问网址 * @param params * @return * @throws ClientProtocolException * @throws IOException */ public String urlencodedToPost(String params) throws ClientProtocolException, IOException{ //设置请求报文头 method.setHeader("Content-type","application/json; charset=utf-8"); method.setHeader("Accept", "application/x-www-form-urlencoded"); //设置请求参数 method.setEntity(new StringEntity(params, Charset.forName("UTF-8"))); //访问接口 HttpResponse response = httpClient.execute(method); //构造返回值 JSONObject message = new JSONObject(); //添加状态码 message.put("StatusCode", String.valueOf(response.getStatusLine().getStatusCode())); //添加内容 message.put("Message", EntityUtils.toString(response.getEntity())); return message.toString(); } }
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/221191.html原文链接:https://javaforall.net
