#JAVA写接口
JAVA一般先编写个数据Model
@ResponseBody //表示返回的是json对象
@RequestMapping(value="/xxx", method = RequestMethod.GET)
public Map<String,Object> xxx(Model model) {
Map<String,Object> returnMsg = new HashMap<String,Object>();
String str=new String("访问JAVA接口返回数据".getBytes("iso-8859-1"),"utf-8");//避免返回数据乱码
returnMsg.put("msg",str );
return returnMsg;
}
#PHP写接口
<?php
$myArray=array("xx"=>"xx");
$myArray["xxx"]="xxx";
echo json_encode($myArray);
?>
#PHP跨域访问JAVA
<?php
function getHttpResponseGET($url) {
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, 0 );
curl_setopt($curl,CURLOPT_RETURNTRANSFER, 1);
$responseText = curl_exec($curl);
curl_close($curl);
return $responseText;
}
$hanzi = rawurlencode("汉字"); //传汉字需要先编码
$url = 'http://xxx.xxx.xxx.xx/xx/xx/xx?xx=xxx&xx=xxx';
var_dump($url);
$responseText = getHttpResponseGET($url);
$obj=json_decode($responseText);
var_dump($responseText);
echo $obj->xxx;
?>
#JAVA跨域访问PHP
<!--http请求-->
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
public static Map<String, String> KuaYu(String url,Map<String , String> map){
Map<String, String> reMap = new HashMap<String, String>();
try{
if(map.size() == 0){
reMap.put("outResult", "0");
reMap.put("outResultReason", "无数据需要发送");
return reMap;
}
HttpClient client = new HttpClient();
//返回结果集
JSONObject jsonObjectResult = new JSONObject();
PostMethod postMethod = new PostMethod(url);
client.getParams().setSoTimeout(15000);
//Part[] parts = { new StringPart("accNumber", "13816032072"),new StringPart("password", "000000")}
Part[] parts = new Part[map.size()];
Map<String , String> mapParas = map;
int i =0;
for(Map.Entry<String, String> entry : mapParas.entrySet()){
parts[i] = new StringPart(entry.getKey().trim(), entry.getValue().trim());
i++;
}
//对于MIME类型的请求,httpclient建议全用MulitPartRequestEntity进行包装
MultipartRequestEntity mre = new MultipartRequestEntity(parts, postMethod.getParams());
postMethod.setRequestEntity(mre);
//执行请求,返回状态码
int status = client.executeMethod(postMethod);
if (status == HttpStatus.SC_OK) {
String result = postMethod.getResponseBodyAsString();
result = new String(result.getBytes("ISO-8859-1"),"UTF-8");//汉字需要编码成UTF-8
jsonObjectResult = JSONObject.parseObject(result);
for(String key:jsonObjectResult.keySet()){
reMap.put(key,jsonObjectResult.get(key).toString());
}
} else {
// 接口请求失败。
reMap.put("outResult", "0");
reMap.put("outResultReason", "请求失败。");
}
}catch(Exception e){
e.printStackTrace();
reMap.put("outResult", "0");
reMap.put("outResultReason", "请求超时。");
}
return reMap;
}
调用:
Map<String , String> map = new HashMap<String , String>();
map.put("xxx", "xxx");
map.put("xxx", "xxx");
String url = "http://xxx.xxx.xxx/xxx/xxx";
Map<String, String> mapResult = UrlUtil.KuaYu(url, map);