您的位置:首页 > 理论基础 > 计算机网络

java 模拟http请求(跨域解决方案)

2017-11-26 21:20 295 查看
1.需要引入的jar包

<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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 跨域 http