java 模擬http請求(跨域解決方案)
阿新 • • 發佈:2019-01-09
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);
}