使用urlconnection和json發送post請求到服務器

使用urlconnection和json發送post請求到服務器
2010-02-22 13:02

客戶端:

***
*HttpURLConnection連接服務器<br>
*<功能詳細描述><br>
*1、通過後臺得到sessionID<br>
*2、檢查MAC地址是否正確<br>
*3、處理從服務器讀取的JSON對象<br>
*4、從服務器讀取對象<br>
*5、得到對象輸出流<br>
*6、設置HttpURLConnection參數<br>
*
* @author "zhaohaiyang"<br>
*@version 版本號 2010-1-14 下午02:01:41<br>
*@see 相關類/方法<br>
**/
public class ConUtils
{

 /**
*通過後臺得到sessionID<br>
*<功能詳細描述><br>
*
* @param parameters
*            登陸信息
* @return 登陸成功返回sessionId 失敗返回“”
* @see [類、類#方法、類#成員]
*/
public static String receiveSessionID(String[] parameters, String[] values)
{
String tempSessionId = "";// SessionID

  URL url = null;// 請求處理的Servlet

  ObjectOutputStream objOutputStrm = null;// 對象輸出流

  InputStream inStrm = null;// 得到HttpURLConnection的輸入流

  HttpURLConnection httpUrlConnection = null;

  try
{
url = new URL("http://192.168.18.109:8080/jj_erp/loginval");

   // 設置HttpURLConnection參數
httpUrlConnection = setURLConnectionProperties(url);

   // 得到對象輸出流
objOutputStrm = getObjOutStream(httpUrlConnection);

   JSONObject obj = new JSONObject();
for (int i = 0; i < parameters.length; i++)
{
obj.put(parameters[i], values[i]);
}
// 向對象輸出流寫出數據,這些數據將存到內存緩衝區中
objOutputStrm.writeObject(obj.toString());
// 刷新對象輸出流,將任何字節都寫入潛在的流中(些處爲ObjectOutputStream)
objOutputStrm.flush();
// 關閉流對象。此時,不能再向對象輸出流寫入任何數據,先前寫入的數據存在於內存緩衝區中,
// 在調用下邊的getInputStream()函數時才把準備好的http請求正式發送到服務器
// objOutputStrm.close();

   // 調用HttpURLConnection連接對象的getInputStream()函數,
// 將內存緩衝區中封裝好的完整的HTTP請求電文發送到服務端。
inStrm = httpUrlConnection.getInputStream(); // <===注意,實際發送請求的代碼段就在這裏

   // 上邊的httpConn.getInputStream()方法已調用,本次HTTP請求已結束,下邊向對象輸出流的輸出已無意義,
// 既使對象輸出流沒有調用close()方法,下邊的操作也不會向對象輸出流寫入任何數據.
// 因此,要重新發送數據時需要重新創建連接、重新設參數、重新創建流對象、重新寫數據、
// 重新發送數據(至於是否不用重新這些操作需要再研究)
// objOutputStrm.writeObject(new String(""));
// httpUrlConnection.getInputStream();

   // 從服務器讀取對象
Object inObj = readObjectFromServer(inStrm);
// 處理從服務器讀取的JSON對象
tempSessionId = doJsonObjectFromServerForSesId(tempSessionId, inObj);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (ProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (JSONException e)
{
e.printStackTrace();
}
finally
{
try
{
if (objOutputStrm != null)
{
objOutputStrm.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
if (inStrm != null)
{
inStrm.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}

  return tempSessionId;
}

 /**
*檢查MAC地址是否正確<br>
*
* @param mac
* @return MAC地址正確返回true 錯誤返回false
*@see [類、類#方法、類#成員]
*/
public static boolean checkMac(String mac)
{

  URL url = null;// 請求處理的Servlet

  boolean flag = false;// MAC地址是否正確

  ObjectOutputStream objOutputStrm = null;// 對象輸出流

  InputStream inStrm = null;// 得到HttpURLConnection的輸入流

  HttpURLConnection httpUrlConnection = null;
try
{
url = new URL("http://192.168.18.109:8080/jj_erp/checkMac");

   // 設置HttpURLConnection參數
httpUrlConnection = setURLConnectionProperties(url);

   // 得到對象輸出流
objOutputStrm = getObjOutStream(httpUrlConnection);

   JSONObject obj = new JSONObject();
obj.put("mac", mac);
// 向對象輸出流寫出數據,這些數據將存到內存緩衝區中
objOutputStrm.writeObject(obj.toString());
// 刷新對象輸出流,將任何字節都寫入潛在的流中(些處爲ObjectOutputStream)
objOutputStrm.flush();
// 關閉流對象。此時,不能再向對象輸出流寫入任何數據,先前寫入的數據存在於內存緩衝區中,
// 在調用下邊的getInputStream()函數時才把準備好的http請求正式發送到服務器
// objOutputStrm.close();

   // 調用HttpURLConnection連接對象的getInputStream()函數,
// 將內存緩衝區中封裝好的完整的HTTP請求電文發送到服務端。
inStrm = httpUrlConnection.getInputStream(); // <===注意,實際發送請求的代碼段就在這裏

   // 上邊的httpConn.getInputStream()方法已調用,本次HTTP請求已結束,下邊向對象輸出流的輸出已無意義,
// 既使對象輸出流沒有調用close()方法,下邊的操作也不會向對象輸出流寫入任何數據.
// 因此,要重新發送數據時需要重新創建連接、重新設參數、重新創建流對象、重新寫數據、
// 重新發送數據(至於是否不用重新這些操作需要再研究)
// objOutputStrm.writeObject(new String(""));
// httpUrlConnection.getInputStream();

   // 從服務器讀取對象
Object inObj = readObjectFromServer(inStrm);
// 處理從服務器讀取的JSON對象
flag = doJsonObjectFromServer(flag, inObj);

  }
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (JSONException e)
{
e.printStackTrace();
}
finally
{

  }

  return flag;
}

 /**
*處理從服務器讀取的JSON對象 用於校驗MAC地址<br>
*<功能詳細描述><br>
*
* @param flag
*            MAC是否正確
* @param inObj
*            從服務器讀到的JSON對象
* @return MAC是否正確
* @throws JSONException
*@see [類、類#方法、類#成員]
*/

 private static boolean doJsonObjectFromServer(boolean flag, Object inObj)
throws JSONException
{
// 做非空處理
if (inObj != null)
{
// 根據得到的序列化對象 構建JSON對象
JSONObject injson = new JSONObject(inObj.toString());
// 拿到JSON對象中 對應key的值
String getStr = injson.getString("returnstring");
if (getStr.equals("true"))
{
flag = true;
}
}
return flag;
}

 private static String doJsonObjectFromServerForSesId(String tempSessionID,
Object inObj) throws JSONException
{
// 做非空處理
if (inObj != null)
{
// 根據得到的序列化對象 構建JSON對象
JSONObject injson = new JSONObject(inObj.toString());
// 拿到JSON對象中 對應key的值
tempSessionID = injson.getString("sessionID");
}
return tempSessionID;
}

 /**
*從服務器讀取對象<br>
*<功能詳細描述><br>
*
* @param inStrm
*            輸入流
* @return 從服務器返回的對象
* @throws IOException
*@see [類、類#方法、類#成員]
*/

 private static Object readObjectFromServer(InputStream inStrm)
throws IOException
{
ObjectInputStream objInStream; // 輸入流 從服務器讀取JSON對象
objInStream = new ObjectInputStream(inStrm);// 輸入流 從服務器讀取JSON對象
Object inObj = null;
try
{
inObj = objInStream.readObject();// 讀取對象
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
return inObj;
}

 /**
*得到對象輸出流<br>
*<功能詳細描述><br>
*
* @param httpUrlConnection
*            後臺與服務器之間的通信
* @return 對象輸出流
* @throws IOException
*@see [類、類#方法、類#成員]
*/

 private static ObjectOutputStream getObjOutStream(
HttpURLConnection httpUrlConnection) throws IOException
{
OutputStream outStrm;// 得到HttpURLConnection的輸出流
ObjectOutputStream objOutputStrm;// 對象輸出流
// 此處getOutputStream會隱含的進行connect(即:如同調用上面的connect()方法,
// 所以在開發中不調用上述的connect()也可以)。
outStrm = httpUrlConnection.getOutputStream();

  // 現在通過輸出流對象構建對象輸出流對象,以實現輸出可序列化的對象。
// 使用JSON傳值
objOutputStrm = new ObjectOutputStream(outStrm);
return objOutputStrm;
}

 /**
*設置HttpURLConnection參數<br>
*<功能詳細描述><br>
*
* @param url
*            請求處理的地址
* @return 後臺與服務器之間的通信連接
* @throws IOException
* @throws ProtocolException
*@see [類、類#方法、類#成員]
*/

 private static HttpURLConnection setURLConnectionProperties(URL url)
throws IOException, ProtocolException
{
HttpURLConnection httpUrlConnection;
URLConnection rulConnection = url.openConnection();// 此處的urlConnection對象實際上是根據URL的
// 請求協議(此處是http)生成的URLConnection類
// 的子類HttpURLConnection,故此處最好將其轉化
// 爲HttpURLConnection類型的對象,以便用到
// HttpURLConnection更多的API.如下:

  httpUrlConnection = (HttpURLConnection) rulConnection;

  // 設置是否向httpUrlConnection輸出,因爲這個是post請求,參數要放在
// http正文內,因此需要設爲true, 默認情況下是false;
httpUrlConnection.setDoOutput(true);

  // 設置是否從httpUrlConnection讀入,默認情況下是true;
httpUrlConnection.setDoInput(true);

  // Post 請求不能使用緩存
httpUrlConnection.setUseCaches(false);

  // 設定傳送的內容類型是可序列化的java對象
// (如果不設此項,在傳送序列化對象時,當WEB服務默認的不是這種類型時可能拋java.io.EOFException)
// httpUrlConnection.setRequestProperty("Content-type",
// "application/x-java-serialized-object");
//   
httpUrlConnection
.setRequestProperty("Content-type", "application/json");

  // 設定請求的方法爲"POST",默認是GET
httpUrlConnection.setRequestMethod("POST");

  try
{
// 連接,從上述至此的配置必須要在connect之前完成,
httpUrlConnection.connect();
httpUrlConnection.setConnectTimeout(1);
httpUrlConnection.setReadTimeout(1);
}
catch (ConnectException e1)
{
if (e1.getMessage().equals("Connection refused: connect"))
{
JOptionPane.showMessageDialog(null, "連接超時");
System.exit(0);
}
}
return httpUrlConnection;
}

 public static void main(String[] args)
{
if (checkMac("40-61-86-69-82-E2"))
{
System.out.println("mac地址校驗成功");
}
else
{
System.out.println("mac地址校驗失敗");
}
}
}

 

服務器端:

checkMac.java

      public class CheckMac extends HttpServlet
{
private static final long serialVersionUID = 1L;
private String    returnstring  = "false";

 @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
InputStream inStream = req.getInputStream();
ObjectInputStream objInStream = new ObjectInputStream(inStream);
Object obj = null;
try
{
obj = objInStream.readObject();
}
catch (ClassNotFoundException e1)
{
e1.printStackTrace();
}
JSONObject json = null;
String mac = "";
JSONObject outjson = new JSONObject();
try
{
if (obj != null)
{
json = new JSONObject(obj.toString());
mac = json.getString("mac");

    if (mac.equals("40-61-86-69-82-E2"))
{
returnstring = "true";
}
}
}
catch (JSONException e)
{
e.printStackTrace();
}
try
{
outjson.put("returnstring", returnstring);
}
catch (JSONException e)
{
e.printStackTrace();
}
resp.setContentType("text/html;charset=utf-8");
OutputStream out = resp.getOutputStream();
ObjectOutputStream objOutputStrm = new ObjectOutputStream(out);
objOutputStrm.writeObject(outjson.toString());
objOutputStrm.flush();
objOutputStrm.close();
}

 

LoginValidate.java

private String    dept    = ""; // 部門
private String    name    = ""; // 姓名
private String    pass    = ""; // 密碼
private String    mac     = ""; // MAC地址
private String    ip     = ""; // IP地址
private String    sessionID   = "";

 @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
InputStream inStream = req.getInputStream();
ObjectInputStream objInStream = new ObjectInputStream(inStream);
Object obj = null;
try
{
obj = objInStream.readObject();
}
catch (ClassNotFoundException e1)
{
e1.printStackTrace();
}
JSONObject json = null;
JSONObject outjson = new JSONObject();
try
{
if (obj != null)
{
json = new JSONObject(obj.toString());
if (json != null)
{
dept = json.getString("dept");
name = json.getString("name");
pass = json.getString("pass");
mac = json.getString("mac");
ip = json.getString("ip");
}
}
}
catch (JSONException e)
{
e.printStackTrace();
}

  /**
* 判斷登陸信息 登陸成功創建Session
*/
if (validateInfo())
{
//   HttpSession session = req.getSession(true);
//   sessionID = session.getId();
sessionID = "sessionid";
}
// 把sessionID放入JSON中
try
{
outjson.put("sessionID", sessionID);
}
catch (JSONException e)
{
e.printStackTrace();
}

  // 將sessionID以JSON方式發送到客戶端
resp.setContentType("text/html;charset=utf-8");
OutputStream out = resp.getOutputStream();
ObjectOutputStream objOutputStrm = new ObjectOutputStream(out);
objOutputStrm.writeObject(outjson.toString());
objOutputStrm.flush();
objOutputStrm.close();
}

 /**
*校驗登陸信息是否正確<br>
*<功能詳細描述><br>
*
* @return 正確返回true 否則返回false
*@see [類、類#方法、類#成員]
*/

 private boolean validateInfo()
{return true;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章