java使用原生代码模拟浏览器访问服务器功能
package com.mycode.util;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
/**
- 使用java 底层代码实现模拟浏览器访问客户端功能
- @author lizhi
*/
public class UrlUtil {
public UrlUtil() {
}
/**
* 获取访问url 地址返回的内容 post 请求,接收json格式参数
* @param url
* @param json
* @return
*/
public static String getContentByUrlPost(String url, String json) {
String backString=null;
InputStream is=null;
OutputStream outwritestream=null;
if (url == null){
return UrlStatus.INVALID_URL.toString();
}
HttpURLConnection httpURLConnection;
try {
URL targetUrl = new URL(url);
URLConnection urlConnection = targetUrl.openConnection();
httpURLConnection = (HttpURLConnection) urlConnection;
//设置超时时间
httpURLConnection.setConnectTimeout(5000);
httpURLConnection.setReadTimeout(5000);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestProperty("Charset", "utf-8");
httpURLConnection.setRequestProperty("Content-Type",
"application/json; charset=UTF-8");
httpURLConnection.setRequestProperty("accept", "application/json");
if (json != null && !"".equals(json)) {
byte writebytes[] = json.getBytes();
httpURLConnection.setRequestProperty("Content-Length",
String.valueOf(writebytes.length));
outwritestream = httpURLConnection.getOutputStream();
outwritestream.write(json.getBytes());
outwritestream.flush();
}
is = httpURLConnection.getInputStream();
backString = new String(getBytes(is), "UTF-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (is != null)
is.close();
if (outwritestream != null)
outwritestream.close();
} catch (IOException e) {
}
}
return backString;
}
/**
* post 请求 原始表单请求
* @param actionURL
* @param parameters
* @return
*/
public static String executePostByUsual(String actionURL, HashMap parameters) {
String response = "";
try {
URL url = new URL(actionURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Charset", "UTF-8");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
String requestContent = "";
Set keys = parameters.keySet();
//拼接请求参数
for (Iterator i$ = keys.iterator(); i$.hasNext();) {
String key = (String) i$.next();
requestContent = (new StringBuilder()).append(requestContent)
.append(key).append("=")
.append((String) parameters.get(key)).append("&")
.toString();
}
requestContent = requestContent.substring(0,
requestContent.lastIndexOf("&"));
//写数据
DataOutputStream ds = new DataOutputStream(
connection.getOutputStream());
ds.write(requestContent.getBytes());
ds.flush();
try {
//读取服务器数据
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream(),
"utf-8"));
String s = "";
for (String temp = ""; (temp = reader.readLine()) != null;){
s = (new StringBuilder()).append(s).append(temp).toString();
}
response = s;
reader.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("No response get!!!");
}
ds.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("Request failed!");
}
return response;
}
/**
* 输入流数据转换至Byte[] 数组中
* @param is
* @return
* @throws IOException
*/
public static byte[] getBytes(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
for (int b = is.read(); b >= 0; b = is.read())
baos.write(b);
return baos.toByteArray();
}
public static void main(String args[]) {
HashMap<String,String> map = new HashMap<String,String>();
map.put("bean.orgType", "1");
map.put("bean.orgCode", "001");
map.put("bean.orgSn", "3");
map.put("bean.orgName",
"\u6211\u7231\u4F60\u4E2D\u56FD,\u6211\u7231\u4F60");
map.put("bean.gpsX", "440106041005");
map.put("bean.gpsY", "440106041005");
map.put("bean.memo", "56_100_1001");
String executePostByUsual = executePostByUsual(
(new StringBuilder())
.append("http://localhost/admin/organization_save.action?nowTime=")
.append((new Date()).getTime()).toString(), map);
System.out.println(executePostByUsual);
}
}
==========================================================
package com.mycode.util;
/**
- Url 访问返回状态码
- @author lz
*/
public enum UrlStatus {
OK("0"),
NOT_SUPPORT("1"),
UNREACHABLE("2"),
INVALID_URL("3");
private String status;
private UrlStatus(String status) {
this.status = status;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}