简单记下httpclientjava实现get,post请求
package com.insigma.siis.local.business.phrsapp.phrsappreg;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONObject;
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;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.HttpEntity;
import org.apache.http.util.EntityUtils;
import org.apache.http.ParseException;
import com.insigma.odin.framework.AppException;
import com.insigma.odin.framework.BSSupport;
/**
* 人社APP企业注册
*
* @author 李维俊
*
*/
public class PhrsappRegBS extends BSSupport {
private String client_id = "___";
private String client_secret = "_____________________________";
private String token_method = "http://________/phrs/oauth/token";
private String reg_method1 = "http://________/phrs/company-user/register";
private String reg_method2 = "http://________/phrs/company-user/info";
private String reg_method3 = "http://________/phrs/company-user/modify";
public static class UTF8PostMethod extends PostMethod{
public UTF8PostMethod(String url){
super(url);
}
@Override
public String getRequestCharSet() {
//return super.getRequestCharSet();
return "utf-8";
}
}
private String sendMsg(NameValuePair[] parametersBody,String methods) {
HttpClient httpClient = new HttpClient();
//
PostMethod postMethod = new UTF8PostMethod(methods);
postMethod.setRequestBody(parametersBody);
String response= "";//要返回的response信息
int statusCode = 0;
try {
statusCode = httpClient.executeMethod(postMethod);
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
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);
// response= methodPost(location,data);//用跳转后的页面重新请求。
} else {
System.err.println("Location field value is null.");
}
} else {
System.out.println(postMethod.getStatusLine());
try {
response= postMethod.getResponseBodyAsString();
} catch (IOException e) {
e.printStackTrace();
}
postMethod.releaseConnection();
}
return response;
}
private String getToken(){
// 核心应用类
NameValuePair[] parametersBody = new NameValuePair[2];
parametersBody[0] = new NameValuePair("client_id", client_id);
parametersBody[1] = new NameValuePair("client_secret",client_secret);
String response = sendMsg(parametersBody,token_method);
JSONObject jobj = JSONObject.fromObject(response);
return jobj.getString("access_token");
}
public String getEncoding(String str) {
String encode = "GB2312";
try {
if (str.equals(new String(str.getBytes(encode), encode))) { //判断是不是GB2312
String s = encode;
return s; //是的话,返回“GB2312“,以下代码同理
}
} catch (Exception exception) {
}
encode = "ISO-8859-1";
try {
if (str.equals(new String(str.getBytes(encode), encode))) { //判断是不是ISO-8859-1
String s1 = encode;
return s1;
}
} catch (Exception exception1) {
}
encode = "UTF-8";
try {
if (str.equals(new String(str.getBytes(encode), encode))) { //判断是不是UTF-8
String s2 = encode;
return s2;
}
} catch (Exception exception2) {
}
encode = "GBK";
try {
if (str.equals(new String(str.getBytes(encode), encode))) { //判断是不是GBK
String s3 = encode;
return s3;
}
} catch (Exception exception3) {
}
return ""; //如果都不是,说明输入的内容不属于常见的编码格式。
}
/**
* 企业注册信息
*
* @param dto
* @return
* @throws AppException
*/
public void save(PhrsappRegDTO dto) throws AppException,URISyntaxException,
ClientProtocolException, IOException {
String encode = getEncoding(dto.getAaa006());
System.out.println(encode);
String aaa001 = dto.getAaa001();
String aaa002 = dto.getAaa002();
String aaa003 = dto.getAaa003();
String aaa004 = dto.getAaa004();
String aaa005 = dto.getAaa005();
String aaa006 = dto.getAaa006();
String aaa007 = dto.getAaa007();
// 示例:提交用户名和密码
System.out.println(getEncoding(aaa006));
System.out.println("aaa003"+aaa003);
System.out.println("aaa004"+aaa004);
NameValuePair[] parametersBody = new NameValuePair[8];
String token = getToken();
parametersBody[0] = new NameValuePair("access_token",token);
parametersBody[1] = new NameValuePair("username",aaa001);
parametersBody[2] = new NameValuePair("password",aaa002);
parametersBody[3] = new NameValuePair("companyName",aaa003);
parametersBody[4] = new NameValuePair("address",aaa004);
parametersBody[5] = new NameValuePair("phoneNumb",aaa005);
parametersBody[6] = new NameValuePair("legalRepr",aaa006);
parametersBody[7] = new NameValuePair("email",aaa007);
//
String response = sendMsg(parametersBody,reg_method1);
System.out.println(response);
JSONObject jobj = JSONObject.fromObject(response);
if(jobj.getString("success").equals("true")){
return;
}else{
throw new AppException("保存出错:"+jobj.getString("message"));
}
}
public String sendGet(String reg_method3,String token, String aaa001) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = reg_method3 + "?access_token=" +token+"&username="+aaa001;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("Charsert", "UTF-8");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
// for (String key : map.keySet()) {
// System.out.println(key + "--->" + map.get(key));
// }
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/**
* 企业信息查询
*
* @param aaa001
* @return
* @throws AppException
*/
public PhrsappRegDTO query(String aaa001) throws AppException,
URISyntaxException, ClientProtocolException, IOException {
PhrsappRegDTO dto = new PhrsappRegDTO();
// 示例:提交用户名和密码
String token = getToken();
//
NameValuePair[] parametersBody = new NameValuePair[2];
parametersBody[0] = new NameValuePair("access_token",token);
parametersBody[1] = new NameValuePair("username",aaa001);
String response = sendMsg(parametersBody,reg_method2);
System.out.println(response);
// response = new String(response.getBytes("utf8"),"GB2312");
// System.out.println("gb2312:"+new String(response.getBytes("GB2312")));
// System.out.println("GBK:"+new String(response.getBytes("GBK")));
// System.out.println("UTF-8:"+new String(response.getBytes("UTF-8")));
// System.out.println("ISO-8859-1:"+new String(response.getBytes("ISO-8859-1")));
// response = new String(response.getBytes("utf8"));
// System.out.println(response);
JSONObject jobj = JSONObject.fromObject(response);
if (jobj.getString("success").equals("true")) {
JSONObject subObj = JSONObject.fromObject(jobj.getString("body"));
if(subObj.has("companyName")){
String aaa003 = new String(subObj.getString("companyName"));
dto.setAaa003(aaa003);
}else{
dto.setAaa003("无");
}
if(subObj.has("address")){
String aaa004 = new String(subObj.getString("address"));
dto.setAaa004(aaa004);
}else{
dto.setAaa004("无");
}
if(subObj.has("phoneNumb")){
dto.setAaa005(subObj.getString("phoneNumb"));
}else{
dto.setAaa005("无");
}
if(subObj.has("legalRepr")){
String aaa006 = new String(subObj.getString("address"));
dto.setAaa006(aaa006);
}else{
dto.setAaa006("无");
}
if(subObj.has("email")){
dto.setAaa007(subObj.getString("email"));
}else{
dto.setAaa007("无");
}
if(subObj.has("createTime")){
Calendar ca = Calendar.getInstance();
ca.setTimeInMillis(Long.parseLong(subObj.getString("createTime")));
dto.setAaa008(ca.get(Calendar.YEAR)+"-"+(ca.get(Calendar.MONTH)+1)+"-"+(ca.get(Calendar.DAY_OF_MONTH)+1)+" "+ca.get(Calendar.HOUR_OF_DAY)+":"+ca.get(Calendar.MINUTE)+":"+ca.get(Calendar.SECOND));
// dto.setAaa008(subObj.getString("createTime"));
}else{
dto.setAaa008("无");
}
if(subObj.has("sts")){
dto.setAaa009(subObj.getString("sts"));
}else{
dto.setAaa009("无");
}
return dto;
} else {
throw new AppException("查询出错:" + jobj.getString("message"));
}
}
/**
* 企业信息更新
*
* @param dto
* @return
* @throws AppException
*/
public void modify(PhrsappRegDTO dto) throws AppException,
URISyntaxException, ClientProtocolException, IOException {
// 示例:提交用户名和密码
NameValuePair[] parametersBody = new NameValuePair[9];
String token = getToken();
String encode = getEncoding(dto.getAaa006());
System.out.println("encode:"+encode);
parametersBody[0] = new NameValuePair("access_token",token);
parametersBody[1] = new NameValuePair("username",dto.getAaa001());
parametersBody[2] = new NameValuePair("password",dto.getAaa002());
parametersBody[3] = new NameValuePair("companyName",dto.getAaa003());
parametersBody[4] = new NameValuePair("address",dto.getAaa004());
parametersBody[5] = new NameValuePair("phoneNumb",dto.getAaa005());
parametersBody[6] = new NameValuePair("legalRepr",dto.getAaa006());
parametersBody[7] = new NameValuePair("email",dto.getAaa007());
parametersBody[8] = new NameValuePair("sts",dto.getAaa009());
//
String response = sendMsg(parametersBody, reg_method3);
System.out.println(response);
JSONObject jobj = JSONObject.fromObject(response);
if (jobj.getString("success").equals("true")) {
// dto.setAaa003(jobj.getString("companyName"));
// dto.setAaa004(jobj.getString("address"));
// dto.setAaa005(jobj.getString("phoneNum"));
// dto.setAaa006(jobj.getString("legalRepr"));
// dto.setAaa007(jobj.getString("email"));
// dto.setAaa008(jobj.getString("createTime"));
// dto.setAaa009(jobj.getString("sts"));
return ;
} else {
throw new AppException("修改出错:" + jobj.getString("message"));
}
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONObject;
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;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.HttpEntity;
import org.apache.http.util.EntityUtils;
import org.apache.http.ParseException;
import com.insigma.odin.framework.AppException;
import com.insigma.odin.framework.BSSupport;
/**
* 人社APP企业注册
*
* @author 李维俊
*
*/
public class PhrsappRegBS extends BSSupport {
private String client_id = "___";
private String client_secret = "_____________________________";
private String token_method = "http://________/phrs/oauth/token";
private String reg_method1 = "http://________/phrs/company-user/register";
private String reg_method2 = "http://________/phrs/company-user/info";
private String reg_method3 = "http://________/phrs/company-user/modify";
public static class UTF8PostMethod extends PostMethod{
public UTF8PostMethod(String url){
super(url);
}
@Override
public String getRequestCharSet() {
//return super.getRequestCharSet();
return "utf-8";
}
}
private String sendMsg(NameValuePair[] parametersBody,String methods) {
HttpClient httpClient = new HttpClient();
//
PostMethod postMethod = new UTF8PostMethod(methods);
postMethod.setRequestBody(parametersBody);
String response= "";//要返回的response信息
int statusCode = 0;
try {
statusCode = httpClient.executeMethod(postMethod);
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
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);
// response= methodPost(location,data);//用跳转后的页面重新请求。
} else {
System.err.println("Location field value is null.");
}
} else {
System.out.println(postMethod.getStatusLine());
try {
response= postMethod.getResponseBodyAsString();
} catch (IOException e) {
e.printStackTrace();
}
postMethod.releaseConnection();
}
return response;
}
private String getToken(){
// 核心应用类
NameValuePair[] parametersBody = new NameValuePair[2];
parametersBody[0] = new NameValuePair("client_id", client_id);
parametersBody[1] = new NameValuePair("client_secret",client_secret);
String response = sendMsg(parametersBody,token_method);
JSONObject jobj = JSONObject.fromObject(response);
return jobj.getString("access_token");
}
public String getEncoding(String str) {
String encode = "GB2312";
try {
if (str.equals(new String(str.getBytes(encode), encode))) { //判断是不是GB2312
String s = encode;
return s; //是的话,返回“GB2312“,以下代码同理
}
} catch (Exception exception) {
}
encode = "ISO-8859-1";
try {
if (str.equals(new String(str.getBytes(encode), encode))) { //判断是不是ISO-8859-1
String s1 = encode;
return s1;
}
} catch (Exception exception1) {
}
encode = "UTF-8";
try {
if (str.equals(new String(str.getBytes(encode), encode))) { //判断是不是UTF-8
String s2 = encode;
return s2;
}
} catch (Exception exception2) {
}
encode = "GBK";
try {
if (str.equals(new String(str.getBytes(encode), encode))) { //判断是不是GBK
String s3 = encode;
return s3;
}
} catch (Exception exception3) {
}
return ""; //如果都不是,说明输入的内容不属于常见的编码格式。
}
/**
* 企业注册信息
*
* @param dto
* @return
* @throws AppException
*/
public void save(PhrsappRegDTO dto) throws AppException,URISyntaxException,
ClientProtocolException, IOException {
String encode = getEncoding(dto.getAaa006());
System.out.println(encode);
String aaa001 = dto.getAaa001();
String aaa002 = dto.getAaa002();
String aaa003 = dto.getAaa003();
String aaa004 = dto.getAaa004();
String aaa005 = dto.getAaa005();
String aaa006 = dto.getAaa006();
String aaa007 = dto.getAaa007();
// 示例:提交用户名和密码
System.out.println(getEncoding(aaa006));
System.out.println("aaa003"+aaa003);
System.out.println("aaa004"+aaa004);
NameValuePair[] parametersBody = new NameValuePair[8];
String token = getToken();
parametersBody[0] = new NameValuePair("access_token",token);
parametersBody[1] = new NameValuePair("username",aaa001);
parametersBody[2] = new NameValuePair("password",aaa002);
parametersBody[3] = new NameValuePair("companyName",aaa003);
parametersBody[4] = new NameValuePair("address",aaa004);
parametersBody[5] = new NameValuePair("phoneNumb",aaa005);
parametersBody[6] = new NameValuePair("legalRepr",aaa006);
parametersBody[7] = new NameValuePair("email",aaa007);
//
String response = sendMsg(parametersBody,reg_method1);
System.out.println(response);
JSONObject jobj = JSONObject.fromObject(response);
if(jobj.getString("success").equals("true")){
return;
}else{
throw new AppException("保存出错:"+jobj.getString("message"));
}
}
public String sendGet(String reg_method3,String token, String aaa001) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = reg_method3 + "?access_token=" +token+"&username="+aaa001;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("Charsert", "UTF-8");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
// for (String key : map.keySet()) {
// System.out.println(key + "--->" + map.get(key));
// }
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/**
* 企业信息查询
*
* @param aaa001
* @return
* @throws AppException
*/
public PhrsappRegDTO query(String aaa001) throws AppException,
URISyntaxException, ClientProtocolException, IOException {
PhrsappRegDTO dto = new PhrsappRegDTO();
// 示例:提交用户名和密码
String token = getToken();
//
NameValuePair[] parametersBody = new NameValuePair[2];
parametersBody[0] = new NameValuePair("access_token",token);
parametersBody[1] = new NameValuePair("username",aaa001);
String response = sendMsg(parametersBody,reg_method2);
System.out.println(response);
// response = new String(response.getBytes("utf8"),"GB2312");
// System.out.println("gb2312:"+new String(response.getBytes("GB2312")));
// System.out.println("GBK:"+new String(response.getBytes("GBK")));
// System.out.println("UTF-8:"+new String(response.getBytes("UTF-8")));
// System.out.println("ISO-8859-1:"+new String(response.getBytes("ISO-8859-1")));
// response = new String(response.getBytes("utf8"));
// System.out.println(response);
JSONObject jobj = JSONObject.fromObject(response);
if (jobj.getString("success").equals("true")) {
JSONObject subObj = JSONObject.fromObject(jobj.getString("body"));
if(subObj.has("companyName")){
String aaa003 = new String(subObj.getString("companyName"));
dto.setAaa003(aaa003);
}else{
dto.setAaa003("无");
}
if(subObj.has("address")){
String aaa004 = new String(subObj.getString("address"));
dto.setAaa004(aaa004);
}else{
dto.setAaa004("无");
}
if(subObj.has("phoneNumb")){
dto.setAaa005(subObj.getString("phoneNumb"));
}else{
dto.setAaa005("无");
}
if(subObj.has("legalRepr")){
String aaa006 = new String(subObj.getString("address"));
dto.setAaa006(aaa006);
}else{
dto.setAaa006("无");
}
if(subObj.has("email")){
dto.setAaa007(subObj.getString("email"));
}else{
dto.setAaa007("无");
}
if(subObj.has("createTime")){
Calendar ca = Calendar.getInstance();
ca.setTimeInMillis(Long.parseLong(subObj.getString("createTime")));
dto.setAaa008(ca.get(Calendar.YEAR)+"-"+(ca.get(Calendar.MONTH)+1)+"-"+(ca.get(Calendar.DAY_OF_MONTH)+1)+" "+ca.get(Calendar.HOUR_OF_DAY)+":"+ca.get(Calendar.MINUTE)+":"+ca.get(Calendar.SECOND));
// dto.setAaa008(subObj.getString("createTime"));
}else{
dto.setAaa008("无");
}
if(subObj.has("sts")){
dto.setAaa009(subObj.getString("sts"));
}else{
dto.setAaa009("无");
}
return dto;
} else {
throw new AppException("查询出错:" + jobj.getString("message"));
}
}
/**
* 企业信息更新
*
* @param dto
* @return
* @throws AppException
*/
public void modify(PhrsappRegDTO dto) throws AppException,
URISyntaxException, ClientProtocolException, IOException {
// 示例:提交用户名和密码
NameValuePair[] parametersBody = new NameValuePair[9];
String token = getToken();
String encode = getEncoding(dto.getAaa006());
System.out.println("encode:"+encode);
parametersBody[0] = new NameValuePair("access_token",token);
parametersBody[1] = new NameValuePair("username",dto.getAaa001());
parametersBody[2] = new NameValuePair("password",dto.getAaa002());
parametersBody[3] = new NameValuePair("companyName",dto.getAaa003());
parametersBody[4] = new NameValuePair("address",dto.getAaa004());
parametersBody[5] = new NameValuePair("phoneNumb",dto.getAaa005());
parametersBody[6] = new NameValuePair("legalRepr",dto.getAaa006());
parametersBody[7] = new NameValuePair("email",dto.getAaa007());
parametersBody[8] = new NameValuePair("sts",dto.getAaa009());
//
String response = sendMsg(parametersBody, reg_method3);
System.out.println(response);
JSONObject jobj = JSONObject.fromObject(response);
if (jobj.getString("success").equals("true")) {
// dto.setAaa003(jobj.getString("companyName"));
// dto.setAaa004(jobj.getString("address"));
// dto.setAaa005(jobj.getString("phoneNum"));
// dto.setAaa006(jobj.getString("legalRepr"));
// dto.setAaa007(jobj.getString("email"));
// dto.setAaa008(jobj.getString("createTime"));
// dto.setAaa009(jobj.getString("sts"));
return ;
} else {
throw new AppException("修改出错:" + jobj.getString("message"));
}
}
}