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");
本文转自 小眼儿 博客园博客,原文链接:http://www.cnblogs.com/hujunzheng/p/5473254.html,如需转载请自行联系原作者