1.带ssl证书
public static JSONObject httpsRequest(String requestUrl, String method, String data) {
JSONObject jsonObject = null;
StringBuffer sb = new StringBuffer();
try {
//创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance( "SSL", "SunJSSE");
sslContext.init(null, tm, new SecureRandom());
//获取SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
//创建HttpsURLConnection对象,并设置其SSLSocketFactory对象
URL url = new URL(requestUrl);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(ssf);
//设置连接参数
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod(method);//设置请求方式
if (method.equals( "GET")) {
conn.connect();
}
if (data != null) {
OutputStream os = conn.getOutputStream();
os.write(data.getBytes( "utf-8"));
os.close();
}
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "utf-8");
BufferedReader br = new BufferedReader(isr);
String str = null;
while ((str = br.readLine()) != null) {
sb.append(str);
}
//清理
br.close();
isr.close();
is.close();
is = null;
conn.disconnect();
//转化为JSON对象
jsonObject = JSONObject.parseObject(sb.toString());
} catch (ConnectException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return jsonObject;
}2.发送post请求/**
* post请求(用于key-value格式的参数)
* @param url
* @param params
* @return
*/
public static String doPost(String url, Map params){
BufferedReader in = null;
try {
// 定义HttpClient
HttpClient client = new DefaultHttpClient();
// 实例化HTTP方法
HttpPost request = new HttpPost();
request.setURI(new URI(url));
//设置参数
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
for (Iterator iter = params.keySet().iterator(); iter.hasNext();) {
String name = (String) iter.next();
String value = String.valueOf(params.get(name));
nvps.add(new BasicNameValuePair(name, value));
//System.out.println(name +"-"+value);
}
request.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
HttpResponse response = client.execute(request);
int code = response.getStatusLine().getStatusCode();
if(code == 200){ //请求成功
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent(),"utf-8"));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
return sb.toString();
}
else{ //
System.out.println("状态码:" + code);
return null;
}
}
catch(Exception e){
e.printStackTrace();
return null;
}
}3.发送post请求另一种形式
/**
* post请求(用于请求json格式的参数)
* @param url
* @param params
* @return
*/
public static String doPost(String url, String params) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);// 创建httpPost
httpPost.setHeader("Accept", "text/plain;charset=utf-8");
httpPost.setHeader("Content-Type", "text/plain;charset=utf-8");
String charSet = "UTF-8";
StringEntity entity = new StringEntity(params, charSet);
httpPost.setEntity(entity);
CloseableHttpResponse response = null;
try {
response = httpclient.execute(httpPost);
StatusLine status = response.getStatusLine();
int state = status.getStatusCode();
if (state == HttpStatus.SC_OK) {
HttpEntity responseEntity = response.getEntity();
String jsonString = EntityUtils.toString(responseEntity);
return jsonString;
}
else{
logger.error("请求返回:"+state+"("+url+")");
}
}
finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
4.发送post请求用于传输文件/**
* post请求(用于请求file传输)
* @param url
* @param instream
* @return
*/
public static String doPost(String url, InputStream instream) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);// 创建httpPost
httpPost.setHeader("Accept", "application/octet-stream");
httpPost.setHeader("Content-Type", "application/octet-stream");
String charSet = "UTF-8";
CloseableHttpResponse response = null;
httpPost.setEntity(new InputStreamEntity(instream));
try {
response = httpclient.execute(httpPost);
StatusLine status = response.getStatusLine();
int state = status.getStatusCode();
if (state == HttpStatus.SC_OK) {
HttpEntity responseEntity = response.getEntity();
String jsonString = EntityUtils.toString(responseEntity);
return jsonString;
}
else{
logger.error("请求返回:"+state+"("+url+")");
}
}
finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}5.发送post用于下载文件
/**
* 用于下载文件
* flag : 用于数据摆渡 , 输出流转换输入流 true为转换
*/
public static Map<String, Object> doPostDownLoad(String url, Map params, OutputStream fos, boolean flag) {
BufferedReader in = null;
try {
// 定义HttpClient
HttpClient client = new DefaultHttpClient();
// 实例化HTTP方法
HttpPost request = new HttpPost();
request.setHeader("Content-Type", "*/*");
request.setURI(new URI(url));
//设置参数
request.setEntity(new StringEntity(FastJsonUtils.toJSONString(params)));
HttpResponse response = client.execute(request);
int code = response.getStatusLine().getStatusCode();
if(code == 200){ //请求成功
Map<String, Object> mapResult = new HashMap<String, Object>();
mapResult.put("isSuccess", true);
if (flag) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
response.getEntity().writeTo(bos);
ByteArrayInputStream swapInputStream = new ByteArrayInputStream(bos.toByteArray());
mapResult.put("inputStream", swapInputStream);
} else {
response.getEntity().writeTo(fos);
}
return mapResult;
}
else{ //
System.out.println("状态码:" + code);
return null;
}
}
catch(Exception e){
e.printStackTrace();
return null;
}
}
1157

被折叠的 条评论
为什么被折叠?



