java 模拟http请求(跨域解决方案)
2017-11-26 21:20
295 查看
1.需要引入的jar包
2.具体写法
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId> <version>4.4.6</version> </dependency>
2.具体写法
//发送数据 @RequestMapping(value="/postJCList",produces="application/json;charset=utf-8") @ResponseBody public String postJCList(@RequestParam(value="mydata") String mydata,@RequestParam(value="url") String url){ JSONObject jsStr = JSONObject.fromObject(mydata); HttpClient httpClient = new DefaultHttpClient(); HttpPost method = new HttpPost(url); method.setHeader("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); int status = 0; String body = null; if (method != null) { try { //添加参数 JSONObject jsob=new JSONObject(); jsob.put("ceshi", "123"); StringEntity entity= new StringEntity(jsStr.toString()); entity.setContentEncoding("UTF-8"); entity.setContentType("application/json"); method.setEntity(entity); long startTime = System.currentTimeMillis(); HttpResponse response = httpClient.execute(method); System.out.println("the http method is:" + method.getEntity()); long endTime = System.currentTimeMillis(); int statusCode = response.getStatusLine().getStatusCode(); System.out.println("状态码:" + statusCode); System.out.println("调用API 花费时间(单位:毫秒):" + (endTime - startTime)); if (statusCode != HttpStatus.SC_OK) { System.out.println("请求失败:" + response.getStatusLine()); status = 1; } //Read the response body body = EntityUtils.toString(response.getEntity(), "UTF-8"); System.out.println(body); } catch (IOException e) { //发生网络异常 System.out.println("exception occurred!\n" + ExceptionUtils.getFullStackTrace(e)); //网络错误 status = 3; } finally { System.out.println("调用接口状态:" + status); } } return body; } // 构建唯一会话Id public static String getSessionId(){ UUID uuid = UUID.randomUUID(); String str = uuid.toString(); return str.substring(0, 8) + str.substring(9, 13) + str.substring(14, 18) + str.substring(19, 23) + str.substring(24); }
相关文章推荐
- ajax跨域后台java两种解决方案
- Java发送Http请求,模拟表单上传文件
- Java模拟http请求调用远程接口工具类(转)
- 用Java模拟Http请求
- java模拟多线程http请求
- java代码模拟http请求
- JAVA模拟发送HTTP请求
- java模拟http请求的代码实现
- 使用java模拟http请求时关于特殊字符的处理+
- JAVA模拟发送HTTP请求
- java模拟http请求 POST
- 关于java模拟http请求的小错误
- java模拟http请求小例子
- 上curl java 模拟http请求
- java模拟http请求
- java模拟http请求调用远程接口工具类
- 关于curl java 模拟http请求
- java 之 模拟http请求
- java 模拟HTTP请求
- java模拟HTTP请求,发送JSON数据