HttpClient示例

package callcenter.common;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

/**
* 提交广告 使用keytool -import -alias "mykey" -file C:\server.cer -keystore
* C:\my.truststore 生成密钥并调用
*
* @author Qian
*
*/
public class ADOperation {

private String IP_ADDRESS = "IPIVR801.HCIPCC.COM";
// private String IP_ADDRESS = "11.1.65.21";
private int PORT = 8443;
private String USERNAME = "IVR01_USER";
private String PASSWORD = "bank6000";
private String KEYSTORE = "C:\\my.truststore";
private String KEYSTOREPWD = "123456";

private DefaultHttpClient httpclient = null;
private HttpHost host = null;
private HttpPost httpPost = null;
private HttpGet httpGet = null;

private class MyFileBody extends FileBody {
private File file;

public MyFileBody(File file) {
super(file);
this.file = file;
}

/**
* overwrite
*/
public String getFilename() {
return file.getPath();
}
}

public ADOperation() {
host = new HttpHost(IP_ADDRESS, PORT, "https");
}

public ADOperation(String ipAddress, int port) {
host = new HttpHost("ipAddress", port, "https");
}

/**
* 注册证书
*
* @throws Exception
*/
private void initialKey() {
httpclient = new DefaultHttpClient();

// 代理设置
// HttpHost proxy = new HttpHost("11.1.9.60", 80);
// httpclient.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY,
// proxy);

httpclient.getCredentialsProvider().setCredentials(
new AuthScope(IP_ADDRESS, PORT),
new UsernamePasswordCredentials(USERNAME, PASSWORD));
KeyStore trustStore = null;
FileInputStream instream = null;
SSLSocketFactory socketFactory = null;
try {
trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
instream = new FileInputStream(new File(KEYSTORE));
trustStore.load(instream, KEYSTOREPWD.toCharArray());
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
instream.close();
} catch (IOException e) {
e.printStackTrace();
}
}

try {
socketFactory = new SSLSocketFactory(trustStore);
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (UnrecoverableKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}

Scheme sch = new Scheme("https", PORT, socketFactory);
httpclient.getConnectionManager().getSchemeRegistry().register(sch);

}

/**
* Get提交方式
*
* @throws Exception
*/
public HttpResponse getHttp(String url) {
HttpResponse response = null;
try {
httpGet = new HttpGet(url);
response = httpclient.execute(httpGet);
System.out.println(response.getStatusLine());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
httpGet.abort();
}
return response;
}

/**
* 关闭浏览器
*/
public void closeClient() {
httpclient.getConnectionManager().shutdown();
}

/**
* 账号登陆
*
* @return
* @throws Exception
*/
public boolean login() {
HttpResponse response = null;
initialKey();
HttpPost httpPost = new HttpPost("/appadmin/main/j_security_check");
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
NameValuePair name = new BasicNameValuePair("j_username", "IVR01_USER");
NameValuePair pass = new BasicNameValuePair("j_password", "bank6000");
NameValuePair appNav = new BasicNameValuePair("appNav", "appadmin");
NameValuePair go = new BasicNameValuePair("go", "Go");
nvps.add(name);
nvps.add(pass);
nvps.add(appNav);
nvps.add(go);
HttpEntity paramEntity = null;
try {
paramEntity = new UrlEncodedFormEntity(nvps, HTTP.UTF_8);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
httpPost.setEntity(paramEntity);
try {
response = httpclient.execute(host, httpPost);
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} finally {
httpPost.abort();
}
// 查看head取localhost值
Header[] header = response.getAllHeaders();
for (int i = 0; i < header.length; i++) {
if (header[i].getName().equals("Location")) {
response = getHttp(header[i].getValue());
}
}
httpPost = new HttpPost("/appadmin/main");
try {
response = httpclient.execute(host, httpPost);
// printEntity(response.getEntity()); // 登陆成功
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
httpPost.abort();
}
return false;
}

/**
* 上传文件
*
* @return
* @throws
*/
public boolean uploadWav(String fileName) {
login();
MultipartEntity entityParam = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
File f = new File(fileName);
try {
entityParam.addPart("request_type", new StringBody("pgd.upload",
"text/plain", Charset.forName("UTF-8")));
entityParam.addPart("TargetURL", new StringBody("/appadmin/upload",
"text/plain", Charset.forName("UTF-8")));
entityParam.addPart("req", new StringBody("newprompt",
"text/plain", Charset.forName("UTF-8")));
entityParam.addPart("currentDir", new StringBody("/zh_CN/AD/",
"text/plain", Charset.forName("UTF-8")));
entityParam.addPart("filename", new StringBody(f.getPath(),
"text/plain", Charset.forName("UTF-8")));
entityParam.addPart("sourcelink", new StringBody("language",
"text/plain", Charset.forName("UTF-8")));
entityParam.addPart("overwrite", new StringBody("null",
"text/plain", Charset.forName("UTF-8")));
entityParam.addPart("srcfile", new StringBody(f.getPath(),
"text/plain", Charset.forName("UTF-8")));
entityParam.addPart("isMultiPart", new StringBody("", "text/plain",
Charset.forName("UTF-8")));
entityParam.addPart("targetfile", new StringBody(f.getName(),
"text/plain", Charset.forName("UTF-8")));
entityParam.addPart("file1", new MyFileBody(f));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
BasicHttpParams params = new BasicHttpParams();
params.setParameter("Content-Transfer-Encoding", "UTF-8");
httpclient.getParams().setParameter("Content-Transfer-Encoding",
"UTF-8");
httpPost = new HttpPost("/appadmin/Prompt?request_type=pgd.upload");
httpPost.setEntity(entityParam);
httpPost.getParams().setParameter("Content-Transfer-Encoding", "UTF-8");

HttpResponse response = null;
try {
response = httpclient.execute(host, httpPost);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
boolean result = false;
if (response.getStatusLine().getStatusCode() == 200) {
result = true;
} else {
result = false;
}
httpPost.abort();
return result;
}

/**
* 删除文件
*
* @return
*/
public boolean deleteFile(String fileName) {
login();
List<NameValuePair> ll = new ArrayList<NameValuePair>();
NameValuePair request_type = new BasicNameValuePair("request_type",
"do.delete.file");
NameValuePair promptName = new BasicNameValuePair("promptName",
fileName);
NameValuePair currentDir = new BasicNameValuePair("currentDir",
"/zh_CN/AD/");
NameValuePair promptFolders = new BasicNameValuePair("promptFolders",
"zh_CN");
NameValuePair deleteFolders = new BasicNameValuePair("deleteFolders",
fileName);
NameValuePair startindex = new BasicNameValuePair("startindex", "0");
NameValuePair wizard = new BasicNameValuePair("wizard", "false");

ll.add(request_type);
ll.add(promptName);
ll.add(deleteFolders);
ll.add(promptFolders);
ll.add(currentDir);
ll.add(wizard);
ll.add(startindex);
HttpEntity e = null;
try {
e = new UrlEncodedFormEntity(ll, HTTP.UTF_8);
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
httpPost = new HttpPost("/appadmin/Prompt");
httpPost.setEntity(e);
try {
HttpResponse response = httpclient.execute(host, httpPost);
System.out.println(response.getStatusLine());
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
httpPost.abort();
return true;
}

public boolean renameFile(String oldName, String newName) {
if (oldName.equals("") || newName.equals("")) {
return false;
}

login();
/*
* String url = "https://" + IP_ADDRESS + ":" + PORT +
* "/appadmin/Prompt?request_type=pgd.rename.file&fileName=" + oldName +
* "&currentDir=%2Fzh_CN%2FAD%2F"; HttpResponse response = getHttp(url);
* System.out.println(printEntity(response.getEntity()));
*/
List<NameValuePair> ll = new ArrayList<NameValuePair>();

NameValuePair request_type = new BasicNameValuePair("request_type",
"do.rename.file");
NameValuePair currentDir = new BasicNameValuePair("currentDir",
"/zh_CN/AD/");
NameValuePair srcFolderName = new BasicNameValuePair("srcFolderName",
oldName);
NameValuePair destFolderName = new BasicNameValuePair("destFolderName",
newName);

ll.add(request_type);
ll.add(currentDir);
ll.add(srcFolderName);
ll.add(destFolderName);

HttpEntity e = null;
try {
e = new UrlEncodedFormEntity(ll, HTTP.UTF_8);
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}

httpPost = new HttpPost("/appadmin/Prompt?request_type=do.rename.file");
httpPost.setEntity(e);

try {
HttpResponse response = httpclient.execute(host, httpPost);
System.out.println(response.getStatusLine());
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
httpPost.abort();

return true;
}

/**
* 添加文件夹
*
* @return
*/
public boolean addNewFile() {
login();
List<NameValuePair> ll = new ArrayList<NameValuePair>();

NameValuePair request_type = new BasicNameValuePair("request_type",
"do.create.folder");
NameValuePair absPath = new BasicNameValuePair("absPath", "/zh_CN/AD/");
NameValuePair folderName = new BasicNameValuePair("folderName", "dd");

ll.add(request_type);
ll.add(absPath);
ll.add(folderName);

HttpEntity e = null;
try {
e = new UrlEncodedFormEntity(ll, HTTP.UTF_8);
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
httpPost = new HttpPost(
"/appadmin/Prompt?request_type=do.create.folder");
httpPost.setEntity(e);

try {
httpclient.execute(host, httpPost);
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
return true;
}

/**
* 跳转到我需要的上传的页面
*/
public boolean gotoUpdateFile() {
login();
String url = "https://"
+ IP_ADDRESS
+ ":"
+ PORT
+ "/appadmin/Prompt?request_type=create.pgd&req=newprompt&filename=''&currentDir=/zh_CN/AD/&sourcelink=language";
getHttp(url);
return true;
}

/**
* 打印页面
*
* @param entity
*/
private String printEntity(HttpEntity entity) {
StringBuffer result = new StringBuffer();
BufferedReader br = null;
try {
if (entity != null) {
br = new BufferedReader(new InputStreamReader(entity
.getContent()));
String line = "";
while ((line = br.readLine()) != null) {
result.append(line + "\n");
}
System.out.println(new String(result));
}
EntityUtils.consume(entity);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
br = null;
}
return new String(result);
}

public static void main(String[] args) throws Exception {
ADOperation ad = new ADOperation();
ad.login();
}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值