Java发送网络请求到PHP,并将PHP处理内容返回到Java程序。
public static String genSig(String ... params){
String requestPath="http://XXXX/index.php";//XXXX表示ip地址,可以查看本机或服务器的ip地址。
URL url;
HttpURLConnection phpConn=null;
try {
//建立连接
url= new URL(requestPath);
phpConn= (HttpURLConnection) url.openConnection();
//连接属性
phpConn.setDoOutput(true);//使用URL连接进行输出
phpConn.setDoInput(true);//使用URL连接进行输入
phpConn.setUseCaches(false);
phpConn.setRequestMethod("POST");
String requestParams="appID="+params[0]+"&secret="+params[1]+"&roomID="+params[2]
+"&userID="+params[3]+"&expire="+params[4]; //请求参数拼接
byte[] requestParamsBytes=requestParams.getBytes("UTF-8");
//设置请求属性
phpConn.setRequestProperty("Content-length",""+requestParamsBytes.length);
phpConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
phpConn.setRequestProperty("Connection","Keep-Alive");//维持长连接
phpConn.setRequestProperty("Charset","UTF-8");
phpConn.connect();//连接
//建立输出流,写入数据
OutputStream outputStream=phpConn.getOutputStream();
outputStream.write(requestParamsBytes);
outputStream.close();
//获取响应状态
int response=phpConn.getResponseCode();
if(HttpURLConnection.HTTP_OK==response){//连接成功
StringBuffer sb=new StringBuffer();
String readLine;
BufferedReader bufferedReader;
bufferedReader=new BufferedReader(new InputStreamReader(phpConn.getInputStream(),"UTF-8"));
while (null!=(readLine=bufferedReader.readLine())){
sb.append(readLine).append("\n");
}
bufferedReader.close();
return sb.toString();
}
else{
System.out.println("连接失败!");
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
if(null!=phpConn){//关闭连接
phpConn.disconnect();
}
}
return null;
}