1、Java模拟POST表单操作 HttpClient的应用及注意事项
http://blog.csdn.net/DL88250/article/details/1699678
View Code
package post;
import java.io.IOException;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
public class PostHttp {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
HttpClient httpClient = new HttpClient();
String url = "http://193.167.13.21/setup.cgi";
PostMethod postMethod = new PostMethod(url);
// 填入各个表单域的值
NameValuePair[] data = {
new NameValuePair("ID", "11"),
new NameValuePair("mtg", "0"),
new NameValuePair("haveCookie", "0"),
new NameValuePair("backID", "30"),
new NameValuePair("psw", "password")
};
// 将表单的值放入postMethod中
postMethod.setRequestBody(data);
// 执行postMethod
int statusCode = 0;
try {
statusCode = httpClient.executeMethod(postMethod);
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// HttpClient对于要求接受后继服务的请求,象POST和PUT等不能自动处理转发
// 301或者302
if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY)
{
// 从头中取出转向的地址
Header locationHeader = postMethod.getResponseHeader("location");
String location = null;
if (locationHeader != null) {
location = locationHeader.getValue();
System.out.println("The page was redirected to:" + location);
}
else {
System.err.println("Location field value is null.");
}
return;
}
else
{
System.out.println(postMethod.getStatusLine());
String str = "";
try {
str = postMethod.getResponseBodyAsString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(str);
}
postMethod.releaseConnection();
return ;
}
}
//这是一个用户认证过程的登陆信息
其中需要的jar包:
1、 commons-httpclient-3.1-rc1.zip http://jakarta.apache.org/commons/httpclient/downloads.html
2、commons-codec-1.3.jar http://jakarta.apache.org/site/downloads/downloads_commons-codec.cgi
3、commons-logging-api.jar 在tomcat5.5中的Tomcat 5.5/bin目录下或者 http://jakarta.apache.org/site/downloads/downloads_commons-logging.cgi
import java.io.IOException;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
public class PostHttp {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
HttpClient httpClient = new HttpClient();
String url = "http://193.167.13.21/setup.cgi";
PostMethod postMethod = new PostMethod(url);
// 填入各个表单域的值
NameValuePair[] data = {
new NameValuePair("ID", "11"),
new NameValuePair("mtg", "0"),
new NameValuePair("haveCookie", "0"),
new NameValuePair("backID", "30"),
new NameValuePair("psw", "password")
};
// 将表单的值放入postMethod中
postMethod.setRequestBody(data);
// 执行postMethod
int statusCode = 0;
try {
statusCode = httpClient.executeMethod(postMethod);
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// HttpClient对于要求接受后继服务的请求,象POST和PUT等不能自动处理转发
// 301或者302
if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY)
{
// 从头中取出转向的地址
Header locationHeader = postMethod.getResponseHeader("location");
String location = null;
if (locationHeader != null) {
location = locationHeader.getValue();
System.out.println("The page was redirected to:" + location);
}
else {
System.err.println("Location field value is null.");
}
return;
}
else
{
System.out.println(postMethod.getStatusLine());
String str = "";
try {
str = postMethod.getResponseBodyAsString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(str);
}
postMethod.releaseConnection();
return ;
}
}
//这是一个用户认证过程的登陆信息
其中需要的jar包:
1、 commons-httpclient-3.1-rc1.zip http://jakarta.apache.org/commons/httpclient/downloads.html
2、commons-codec-1.3.jar http://jakarta.apache.org/site/downloads/downloads_commons-codec.cgi
3、commons-logging-api.jar 在tomcat5.5中的Tomcat 5.5/bin目录下或者 http://jakarta.apache.org/site/downloads/downloads_commons-logging.cgi
2、java应用程序获取ArcGIS REST服务
http://www.cnblogs.com/computer-lzy/archive/2011/03/15/1984962.html
View Code
package com.javaeedev;
import java.util.HashMap;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;
import org.codehaus.jackson.map.MappingJsonFactory;
public class json4 {
private static String URL = "http://m.weather.com.cn/data/101070201.html";// 请求的地址,一个返回JSON格式数据地址
private static HttpClient client;
private static GetMethod getMethod;
/**
* 静态块初始化所需对象
*/
static {
client = new HttpClient();
//设置代理,如果没有使用代理,略去该句
client.getHostConfiguration().setProxy("10.60.30.90", 3128);
getMethod = new GetMethod(URL);
}
/**
* 获取获得的Json结果
*
* @return
*/
public static String getJsonText() {
System.out.println("json2");
String jsonText = null;
try {
System.out.println("1"+jsonText);
int status = client.executeMethod(getMethod);
System.out.println(status);
if (status == HttpStatus.SC_OK) {// HTTP 200 OK
jsonText = getMethod.getResponseBodyAsString();// 获取字符串形式的结果,建议使用流式结果
}
} catch (Exception e) {
System.out.println("2"+jsonText);
System.err.println(e);
}
System.out.println("3"+jsonText);
return jsonText;
}
/**
* 处理Json结果并封装Bean
*
* @param jsonText
* @return
*/
public static Weather getWeatherBean(String jsonText) {
System.out.println("json3");
// Weather对象
Weather weather = new Weather();
System.out.println(jsonText);
try {
JsonFactory jsonFactory = new MappingJsonFactory();
// Json解析器
JsonParser jsonParser = jsonFactory.createJsonParser(jsonText);
// 跳到结果集的开始
jsonParser.nextToken();
// 接受结果的HashMap
HashMap<String, String> map = new HashMap<String, String>();
// while循环遍历Json结果
while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
// 跳转到Value
jsonParser.nextToken();
// 将Json中的值装入Map中
map.put(jsonParser.getCurrentName(), jsonParser.getText());
}
// 将数据封装
weather.setCity(map.get("city"));
weather.setDate(map.get("date_y"));
weather.setLunarDate(map.get("date"));
weather.setWeek(map.get("week"));
weather.setFcTime(map.get("fchh"));
weather.setTemperature(map.get("temp1"));
weather.setWeather(map.get("weather1"));
weather.setWind(map.get("wind1"));
} catch (Exception e) {
System.err.println(e);
}
return weather;
}
/**
* 主函数
*
* @param args
*/
public static void main(String[] args) {
System.out.println("json1");
System.out.println(getWeatherBean(getJsonText()));
}
}
注意:一般情况下,需要你在项目中引用几个jar包的:
jackson-core-asl-1.4.0.jar,
jackson-mapper-asl-1.4.0.jar,
json.jar
json-lib-2.4-jdk15.jar
import java.util.HashMap;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;
import org.codehaus.jackson.map.MappingJsonFactory;
public class json4 {
private static String URL = "http://m.weather.com.cn/data/101070201.html";// 请求的地址,一个返回JSON格式数据地址
private static HttpClient client;
private static GetMethod getMethod;
/**
* 静态块初始化所需对象
*/
static {
client = new HttpClient();
//设置代理,如果没有使用代理,略去该句
client.getHostConfiguration().setProxy("10.60.30.90", 3128);
getMethod = new GetMethod(URL);
}
/**
* 获取获得的Json结果
*
* @return
*/
public static String getJsonText() {
System.out.println("json2");
String jsonText = null;
try {
System.out.println("1"+jsonText);
int status = client.executeMethod(getMethod);
System.out.println(status);
if (status == HttpStatus.SC_OK) {// HTTP 200 OK
jsonText = getMethod.getResponseBodyAsString();// 获取字符串形式的结果,建议使用流式结果
}
} catch (Exception e) {
System.out.println("2"+jsonText);
System.err.println(e);
}
System.out.println("3"+jsonText);
return jsonText;
}
/**
* 处理Json结果并封装Bean
*
* @param jsonText
* @return
*/
public static Weather getWeatherBean(String jsonText) {
System.out.println("json3");
// Weather对象
Weather weather = new Weather();
System.out.println(jsonText);
try {
JsonFactory jsonFactory = new MappingJsonFactory();
// Json解析器
JsonParser jsonParser = jsonFactory.createJsonParser(jsonText);
// 跳到结果集的开始
jsonParser.nextToken();
// 接受结果的HashMap
HashMap<String, String> map = new HashMap<String, String>();
// while循环遍历Json结果
while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
// 跳转到Value
jsonParser.nextToken();
// 将Json中的值装入Map中
map.put(jsonParser.getCurrentName(), jsonParser.getText());
}
// 将数据封装
weather.setCity(map.get("city"));
weather.setDate(map.get("date_y"));
weather.setLunarDate(map.get("date"));
weather.setWeek(map.get("week"));
weather.setFcTime(map.get("fchh"));
weather.setTemperature(map.get("temp1"));
weather.setWeather(map.get("weather1"));
weather.setWind(map.get("wind1"));
} catch (Exception e) {
System.err.println(e);
}
return weather;
}
/**
* 主函数
*
* @param args
*/
public static void main(String[] args) {
System.out.println("json1");
System.out.println(getWeatherBean(getJsonText()));
}
}
注意:一般情况下,需要你在项目中引用几个jar包的:
jackson-core-asl-1.4.0.jar,
jackson-mapper-asl-1.4.0.jar,
json.jar
json-lib-2.4-jdk15.jar
3、使用httpclient的PostMethod.setRequestBody()方法,发送一个xml字符串或流文件
View Code
使用httpclient的PostMethod.setRequestBody()方法,发送一个xml字符串或流文件
如下:
HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod(this._url);
postMethod.setRequestBody("<?xml version=\"1.0\" encoding=\"UTF-8\"><root><flag>1</flag></root>");
或者
postMethod.setRequestBody(new FileInputStream(new File("")));
如下:
HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod(this._url);
postMethod.setRequestBody("<?xml version=\"1.0\" encoding=\"UTF-8\"><root><flag>1</flag></root>");
或者
postMethod.setRequestBody(new FileInputStream(new File("")));
4、java中返回的JSON对象转换成List用法
View Code
//调用URL --分页
String str = CommonConstant.getPhotoAlbumByUserIdURL() + userid + "&pageNo="
+ paginationDto.getPageNum() + "&pageSize=" + paginationDto.getRowsPerPage();
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(str);
List photoAlbumList = new ArrayList();
try {
client.executeMethod(method);
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String returnJson = "";
try {
returnJson = method.getResponseBodyAsString();//返回json字符串值
System.out.println("---------------------returnJson---------------------------------" + returnJson);
if(returnJson != null && returnJson != ""){
String strJson = returnJson.replace("?(", "").replace(")", "").replace(";", "");
if(strJson.startsWith("{")){
JSONObject jsonObject = JSONObject.fromObject(strJson);
String code = jsonObject.getString("code").toString();
if("200".equals(code)){
JSONArray jsonArray = JSONArray.fromObject(jsonObject.get("result"));
JSONObject jsonObj = jsonArray.getJSONObject(0);
JSONArray dataArray = JSONArray.fromObject(jsonObj.get("data"));
for (int i = 0, len = dataArray.size(); i < len; i++) {
PhotoAlbumVO vo = new PhotoAlbumVO();
JSONObject jsonVideo = dataArray.getJSONObject(i);
vo.setId(jsonVideo.get("id").toString());
vo.setUserid(jsonVideo.get("userid").toString());
vo.setTitle(jsonVideo.get("title").toString());
vo.setIntro(jsonVideo.get("intro").toString());
vo.setCoverPath(jsonVideo.get("cover_path").toString());
vo.setType(Integer.parseInt(jsonVideo.get("type").toString()));
vo.setNumberPhoto(Integer.parseInt(jsonVideo.get("number_photo").toString()));
vo.setCreatedTime(DateTimeUtils.parseFullDateTime(DateUtil.getDateTimeByMillisecond(jsonVideo.get("created_time").toString())));
vo.setUpdatedTime(DateTimeUtils.parseFullDateTime(DateUtil.getDateTimeByMillisecond(jsonVideo.get("updated_time").toString())));
photoAlbumList.add(vo);
}
JSONArray pageArray = JSONArray.fromObject(jsonObj.get("page"));
JSONObject pagerObj = pageArray.getJSONObject(0);
JSONArray pagerArray = JSONArray.fromObject(pagerObj.get("pager"));
JSONObject pagerObj1 = pagerArray.getJSONObject(0);
paginationDto.setTotalRowNum(Long.valueOf(pagerObj1.get("pageSum").toString()));
}
}
}
} catch (IOException e1) {
e1.printStackTrace();
}finally{
//使用完成后要释放链接
method.releaseConnection();
}
System.out.println("===========================================size"+photoAlbumList.size());
return photoAlbumList;
String str = CommonConstant.getPhotoAlbumByUserIdURL() + userid + "&pageNo="
+ paginationDto.getPageNum() + "&pageSize=" + paginationDto.getRowsPerPage();
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(str);
List photoAlbumList = new ArrayList();
try {
client.executeMethod(method);
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String returnJson = "";
try {
returnJson = method.getResponseBodyAsString();//返回json字符串值
System.out.println("---------------------returnJson---------------------------------" + returnJson);
if(returnJson != null && returnJson != ""){
String strJson = returnJson.replace("?(", "").replace(")", "").replace(";", "");
if(strJson.startsWith("{")){
JSONObject jsonObject = JSONObject.fromObject(strJson);
String code = jsonObject.getString("code").toString();
if("200".equals(code)){
JSONArray jsonArray = JSONArray.fromObject(jsonObject.get("result"));
JSONObject jsonObj = jsonArray.getJSONObject(0);
JSONArray dataArray = JSONArray.fromObject(jsonObj.get("data"));
for (int i = 0, len = dataArray.size(); i < len; i++) {
PhotoAlbumVO vo = new PhotoAlbumVO();
JSONObject jsonVideo = dataArray.getJSONObject(i);
vo.setId(jsonVideo.get("id").toString());
vo.setUserid(jsonVideo.get("userid").toString());
vo.setTitle(jsonVideo.get("title").toString());
vo.setIntro(jsonVideo.get("intro").toString());
vo.setCoverPath(jsonVideo.get("cover_path").toString());
vo.setType(Integer.parseInt(jsonVideo.get("type").toString()));
vo.setNumberPhoto(Integer.parseInt(jsonVideo.get("number_photo").toString()));
vo.setCreatedTime(DateTimeUtils.parseFullDateTime(DateUtil.getDateTimeByMillisecond(jsonVideo.get("created_time").toString())));
vo.setUpdatedTime(DateTimeUtils.parseFullDateTime(DateUtil.getDateTimeByMillisecond(jsonVideo.get("updated_time").toString())));
photoAlbumList.add(vo);
}
JSONArray pageArray = JSONArray.fromObject(jsonObj.get("page"));
JSONObject pagerObj = pageArray.getJSONObject(0);
JSONArray pagerArray = JSONArray.fromObject(pagerObj.get("pager"));
JSONObject pagerObj1 = pagerArray.getJSONObject(0);
paginationDto.setTotalRowNum(Long.valueOf(pagerObj1.get("pageSum").toString()));
}
}
}
} catch (IOException e1) {
e1.printStackTrace();
}finally{
//使用完成后要释放链接
method.releaseConnection();
}
System.out.println("===========================================size"+photoAlbumList.size());
return photoAlbumList;
5、