1.HttpURLConnection發送url請求
public class JavaRequest {private static final String BASE_URL = "http://localhost:8080/dsdemo/";public static String userToken = null;public static String problemName = null;public static String sendPost(String sufUrl, JSONObject params) {DataOutputStream out = null;BufferedReader in = null;String result = "";try {URL realUrl = new URL(BASE_URL+sufUrl);// 打開和URL之間的連接HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestMethod("POST"); // 設置請求方式 connection.setRequestProperty("Connection", "Keep-Alive");connection.connect();out = new DataOutputStream (connection.getOutputStream());// 發送請求參數,防止中文亂碼out.write(jsonToUrlParams(params).getBytes("UTF-8"));// flush輸出流的緩沖 out.flush();// 定義BufferedReader輸入流來讀取URL的響應in = new BufferedReader(new InputStreamReader(connection.getInputStream()));String line;while ((line = in.readLine()) != null) {result += line;}} catch (Exception e) {System.out.println("發送 POST 請求出現異常!");e.printStackTrace();}//使用finally塊來關閉輸出流、輸入流finally{try{if(out!=null){out.close();}if(in!=null){in.close();}}catch(IOException ex){ex.printStackTrace();}}System.out.println(result);return result;} private static String jsonToUrlParams(JSONObject params){StringBuilder sb = new StringBuilder();sb.append("userToken=").append(userToken);for(Iterator<?> it = params.keys(); it.hasNext(); ){String key = (String) it.next();sb.append("&").append(key).append("=").append(params.get(key));}return sb.toString();} }
遺留問題:
a.按照網上說的發送 json格式的字符串,但是后臺無法接收到。所以這里將jsonObject轉化成 url 參數的形式。
b.jquery發送json格式的數據是可以接收到的。
<script type="text/javascript">var sendData = {username: "hjz",password: "123"};(function (){$.ajax({ type:'post', url:'http://localhost:8080/dsdemo/userRegister', data: sendData, dataType:'json', success:function(data){ alert(JSON.stringify(data));} ,error: function(data){alert(JSON.stringify(data));}}); })(); </script>
?
另外可能會出現中文亂碼的問題:
a. 首先發送數據利用DataOutputStream out.write(jsonToUrlParams(params).getBytes("UTF-8"));
b. 接收后臺 response.setCharacterEncoding("utf-8");
?? ??? ? request.setCharacterEncoding("utf-8");