package cn.com.chinautrust.ssoserver.common;java
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;json
import net.sf.json.JSONObject;app
/**
*
*
* @ClassName : HttpReqUtil
*
* @Description : HTTP請求用到的GET和POST的請求方式
*
* @author : yq
*
* @date : 2018年4月18日 下午5:44:29
*
*
*/
public class HttpReqUtil {
/**
*
* @Title : get
* @Description : GET請求方式
* @author : yq
* @param :
* @return : JSONObject
* @throws:
*/
public static String get(String url){
HttpURLConnection http = null;
InputStream is = null;
try {
URL urlGet = new URL(url);
http = (HttpURLConnection) urlGet.openConnection();post
http.setRequestMethod("GET");
http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
System.setProperty("sun.net.client.defaultReadTimeout", "30000");url
http.connect();.net
is =http.getInputStream();
int size =is.available();
byte[] jsonBytes =new byte[size];
is.read(jsonBytes);
String message=new String(jsonBytes,"UTF-8");
return message;
} catch (Exception e) {
return null;
}finally {
if(null != http) http.disconnect();
try {
if (null != is) is.close();
}catch (IOException e){
e.printStackTrace();
}
}code
}orm
/**
*
* @Title : post
* @Description : POST的請求方式
* @author : yq
* @param :
* @return : String
* @throws:
*/
public static String post(String url,String data){
HttpURLConnection http = null;
PrintWriter out = null;
BufferedReader reader = null;
try {
//建立鏈接
URL urlPost = new URL(url);
http = (HttpURLConnection) urlPost
.openConnection();
http.setDoOutput(true);
http.setDoInput(true);
http.setRequestMethod("POST");
http.setUseCaches(false);
http.setInstanceFollowRedirects(true);
http.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");server
http.connect();ip
//POST請求
OutputStreamWriter outWriter = new OutputStreamWriter(http.getOutputStream(), "utf-8");
out = new PrintWriter(outWriter);
out.print(data);
out.flush();
out.close();
out = null;
//讀取響應
reader = new BufferedReader(new InputStreamReader(
http.getInputStream()));
String lines;
StringBuffer sb = new StringBuffer("");
while ((lines = reader.readLine()) != null) {
lines = new String(lines.getBytes(), "utf-8");
sb.append(lines);
}
reader.close();
reader = null;
System.out.println(sb.toString());
return sb.toString();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}finally {
if(null != http) http.disconnect();
if(null != out) out.close();
try{
if(null != reader) reader.close();
}catch (IOException e){
e.printStackTrace();
}
}
} }