方法一:
public static String doPostJson(String interfaceUrl, Object jsonObject) throws Exception {
String encoding = "UTF-8";
String contentType = "application/json";
String requestMethod = "POST";
Gson gson = new Gson();
String stringJson = gson.toJson(jsonObject);
StringBuffer result = new StringBuffer();
URLConnection connection = null;
HttpURLConnection httpConn = null;
try {
URL url = new URL(interfaceUrl);
connection = url.openConnection();
httpConn = (HttpURLConnection) connection;
if (stringJson != null) {
byte[] b = stringJson.getBytes(encoding);
// 设置 http发送相关属性
httpConn.setRequestProperty("Content-Length", String.valueOf(b.length));
}
httpConn.setRequestProperty("Accept-Charset", encoding);
httpConn.setRequestProperty("Content-type", contentType);
httpConn.setRequestProperty("contentType", encoding);
httpConn.setRequestMethod(requestMethod.toUpperCase());
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
if (stringJson != null && !stringJson.equals("")) {
// 写消息
OutputStream out = httpConn.getOutputStream();
try {
out.write(stringJson.getBytes(encoding));
} finally {
out.flush();
out.close();
}
}
int returnCode = httpConn.getResponseCode();
if (returnCode != 200) {
throw new Exception("连接异常,状态码[" + returnCode + "]");
}
// 读取结果
InputStreamReader isr = new InputStreamReader(httpConn.getInputStream(), encoding);
BufferedReader in = new BufferedReader(isr);
try {
String inputLine = in.readLine();
while (null != inputLine) {
result.append(inputLine);
inputLine = in.readLine();
}
} finally {
if (in != null) {
in.close();
}
if (isr != null) {
isr.close();
}
}
} catch (Exception e) {
throw e;//请求失败后把异常往外抛
} finally {
if (httpConn != null) {
httpConn.disconnect();
}
}
return result.toString();
}
方法二:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import lsyj.api.fenxiao.utils.BaseExceptionDealWith;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
public class HttpSimpleImpl {
/**
* 默认的字符串格式
*/
private static String DEF_CHARSET="UTF-8";
/**
* 默认文件类型
*/
private static String DEF_FILE_TYPE="text/json";
/**
* 设置请求超时时间 单位毫秒
*/
private int connectionTimeout=30000;
/**
* 设置等待数据超时时间 单位毫秒
*/
private int soTiemout=600000;
public HttpSimpleImpl(){
}
public HttpSimpleImpl(int connectionTimeout,int soTiemout){
if(connectionTimeout>0)
this.connectionTimeout=connectionTimeout;
if(soTiemout>=0){
this.soTiemout=soTiemout;
}
}
/**
* get请求
* @param showUrl
* @param map
* @return
* @throws Exception
*/
public String simpleGet(String showUrl) throws Exception{
GetMethod getMethod = new GetMethod(showUrl);
HttpMethodParams methodParams = getMethod.getParams();
methodParams.setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, DEF_CHARSET);
methodParams.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
HttpClient httpClient = new HttpClient();
HttpConnectionManager connectionManager = httpClient.getHttpConnectionManager();
HttpConnectionManagerParams connectionManagerParams = connectionManager.getParams();
connectionManagerParams.setConnectionTimeout(30000);//
connectionManagerParams.setSoTimeout(30000);//
try {
int statusCode = httpClient.executeMethod(getMethod);
if (statusCode != HttpStatus.SC_OK) {
throw new Exception(" - 异常:http请求返回码错误"+statusCode);
}
InputStream in= getMethod.getResponseBodyAsStream();
BufferedReader br=new BufferedReader(new InputStreamReader(in,DEF_CHARSET));
StringBuffer result=new StringBuffer();
String temp="";
while((temp=br.readLine())!=null){
result.append(temp);
}
return result.toString();
} catch (Exception e) {
throw new Exception(" - 异常:Get请求异常 - 原因描述:"+BaseExceptionDealWith.getBaseExceptionString(e));
}finally{
getMethod.releaseConnection();
}
}
/**
* 简单那的post请求
* @param url 请求地址
* @param postData json格式参数
* @return json字符串
* @throws Exception
*/
public String simplePost(String url,String postData) throws Exception{
if(SimpleUtil.isNullOrTrim(url)||SimpleUtil.isNullOrTrim(postData)){
throw new Exception("url为空,请求内容为空");
}
HttpClient httpClient=new HttpClient();
HttpConnectionManager manager=httpClient.getHttpConnectionManager();
HttpConnectionManagerParams managerPrams=manager.getParams();
managerPrams.setConnectionTimeout(connectionTimeout);
managerPrams.setSoTimeout(soTiemout);
PostMethod postMethod=new PostMethod(url);
postMethod.addRequestHeader("Content-Type", "application/json");
try {
RequestEntity requestEntity=new StringRequestEntity(postData, DEF_FILE_TYPE, DEF_CHARSET);
postMethod.setRequestEntity(requestEntity);
int statusCode=httpClient.executeMethod(postMethod);
if(statusCode!=HttpStatus.SC_OK){
throw new Exception("请求返回状态码错误!状态码:"+statusCode);
}
InputStream in=postMethod.getResponseBodyAsStream();
BufferedReader br=new BufferedReader(new InputStreamReader(in, DEF_CHARSET));
StringBuffer sbResult=new StringBuffer();
String temp="";
while((temp=br.readLine())!=null){
sbResult.append(temp);
}
if(sbResult==null||sbResult.length()<=0)
throw new Exception("返回结果为空!");
return sbResult.toString();
} catch (UnsupportedEncodingException e) {
throw e;
} catch (HttpException e) {
throw e;
} catch (IOException e) {
throw e;
}finally{
postMethod.releaseConnection();
}
}
}
在