用java进行测试php写的接口
<?php
/*
* @Author: anchen
* @Date: 2018-07-06 13:53:19
* @Last Modified by: anchen
* @Last Modified time: 2018-07-06 19:22:44
*/
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Origin, X-Requested-With,Content-Type,Accept");
header("Access-Control-Allow-Methods: GET, POST , PUT,DELETE");
$Json = array('User_Id' => "1", 'User_Name' =>"LiMing", 'User_Department' => "RuiJie", 'Password' => "88888");
echo json_encode($Json,JSON_UNESCAPED_UNICODE);
以上是php代码,主要封装成为json数据,header中的东西是解决跨域调用。然后在appach(2.4.9版本--wamp2.5集成环境)配置文件中配置 Ruquire all granted 和#Require local,就是配置成局域网可以访问。
package test;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import java.net.URL;
import sun.net.www.protocol.http.HttpURLConnection;
public class TestJava {
public static void main(String[] args) {
boolean result=false;
try {
String url ="http://localhost:80/work1/test.php";
String json= TestJava.getHttpResponse(url);
System.out.println(json);
} catch (Exception e) {
e.printStackTrace();
}
/*String url ="http://localhost:80/work1/test.php";
try {
String jsonstr=TestJava.getJsonString(url);
System.out.print(jsonstr);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
public static String getHttpResponse(String allConfigUrl) {
BufferedReader in = null;
StringBuffer result = null;
try {
URI uri = new URI(allConfigUrl);
URL url = uri.toURL();
System.out.println(url);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Charset", "utf-8");
connection.connect();
result = new StringBuffer();
//读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
return result.toString();
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return null;
}
public static String getJsonString(String urlPath) throws Exception {
URL url = new URL(urlPath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream inputStream = connection.getInputStream();
// 对应的字符编码转换
Reader reader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(reader);
String str = null;
StringBuffer sb = new StringBuffer();
while ((str = bufferedReader.readLine()) != null) {
sb.append(str);
}
reader.close();
connection.disconnect();
return sb.toString();
}
}