HttpClient parameter 和body 传输同时进行

package com.uxsino.simo.collector.connections;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Charsets;
import com.google.gson.JsonObject;
import com.uxsino.commons.utils.StringUtils;
import com.uxsino.simo.connections.AbstractConnection;
import com.uxsino.simo.connections.exception.SimoConnectionException;
import com.uxsino.simo.connections.target.SimoAgentTarget;
import lombok.Data;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import springfox.documentation.spring.web.json.Json;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SimoAgentConnection extends AbstractConnection<SimoAgentTarget> {
static Logger logger = LoggerFactory.getLogger(HTTPConnection.class);

private CloseableHttpClient client;

private String urlBase;

private static int DEFAULT_TIMEOUT_MS = 50000;

private static int DEFAULT_TIMEOUT_CONNECT_MS = 2000;

static {
System.setProperty("http.maxConnections", "5000");
}

@Data
class AgentCmd {
private String cmd;

private Map<String, String> args;

AgentCmd(String cmd, Map<String, String> args) {
this.cmd = cmd;
this.args = args;
}
}

@Data
public static class Target{
String username;
String password;
String cmd;
String timeReg;
String timeFormat;
String fileMatchingRule;
}

public static void main(String[] args) {
SimoAgentTarget simoAgentTarget = new SimoAgentTarget();
Target target = new Target();

simoAgentTarget.setUsername("uxsino");
simoAgentTarget.setPassword("1234");
simoAgentTarget.host = "localhost";
simoAgentTarget.port = 55555;
simoAgentTarget.passwordEncrypted = false;
SimoAgentConnection simoAgentConnection = new SimoAgentConnection();
try {
simoAgentConnection.connect(simoAgentTarget);
} catch (Exception e) {
e.printStackTrace();
System.out.println("simoAgent 连接失败");
}
if(simoAgentConnection.isConnected()){
try {
String ss = simoAgentConnection.exec(simoAgentConnection.createCmdPattern("ipconfig")).toString();
System.out.println(ss);
} catch (SimoConnectionException e) {
e.printStackTrace();
System.out.println("simoAgent 获取数据时失败");
}
}else{

}
}

public String createCmdPattern(String cmdPattern){
JSONObject json = new JSONObject();
json.put("cmd",cmdPattern);
return json.toJSONString();
}


@Override
public int connect(SimoAgentTarget target) {
this.target = target;
super.connect(target);
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
HttpClientBuilder builder = HttpClientBuilder.create();
builder.setDefaultCredentialsProvider(credentialsProvider);
client = builder.build();
urlBase = "http://" + target.host + ":" + target.port;
connected = true; // not really connected
state = 1;
return state;
}



private Object exec(Object cmdPattern) throws SimoConnectionException {
String cmdStr = urlBase + "/main/exec?username=uxsino&password=1234";
HttpPost post = new HttpPost(cmdStr);
List<NameValuePair> list = new ArrayList<NameValuePair>();
if(StringUtils.isNotBlank(target.getProperty("timeReg"))){
list.add(new BasicNameValuePair("timeReg", target.getProperty("timeReg")));
}
if(StringUtils.isNotBlank(target.getProperty("timeFormat"))){
list.add(new BasicNameValuePair("timeFormat", target.getProperty("timeFormat")));
}
if(StringUtils.isNotBlank(target.getFileMatchingRule())){
list.add(new BasicNameValuePair("fileMatchingRule", target.getFileMatchingRule()));
}
list.add(new BasicNameValuePair("path", target.getPath()));
list.add(new BasicNameValuePair("username","uxsino"));
list.add(new BasicNameValuePair("password","1234"));
list.add(new BasicNameValuePair("cmd",cmdPattern.toString()));
// try {
Target targets = new Target();
targets.setCmd("ipconfig");
targets.setUsername("uxsino");
targets.setPassword("1234");
String s = JSON.toJSONString(targets);
System.out.println(s);
post.setEntity(new StringEntity(s, Charsets.UTF_8));
System.out.println(s);
// post.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// }
int timeoutMs = target.getTimeout() < DEFAULT_TIMEOUT_MS ? DEFAULT_TIMEOUT_MS : target.getTimeout();
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeoutMs)// 获取数据的超时时间
.setConnectTimeout(DEFAULT_TIMEOUT_CONNECT_MS)// 建立连接的超时时间
.setConnectionRequestTimeout(timeoutMs)// 数据传输超时时间
.build();
post.setConfig(requestConfig);
HttpParams httpParams = new BasicHttpParams();
httpParams.setParameter("username","uxsino");
httpParams.setParameter("password","1234");
post.setParams(httpParams) ;
post.setHeader("Content-Type", "application/json; charset=UTF-8");

HttpEntity entity = null;
try {
HttpResponse response = client.execute(post);
entity = response.getEntity();
InputStream in = entity.getContent();
ByteArrayOutputStream resultByte = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) != -1) {
resultByte.write(buffer, 0, length);
}
String result = resultByte.toString("GBK");
try {
System.out.println(result);
return result;
// JSONObject res = JSON.parseObject(result);
// return res;
} catch (Exception e) {
logger.warn("{}", e);
return null;
}
} catch (IOException e) {
logger.error("error executing cmd in http connection", e);
throw new SimoConnectionException(e);
} finally {
EntityUtils.consumeQuietly(entity);
}
}

@Override
public Object execCmd(Object cmdPattern) throws SimoConnectionException {
JSONObject res = (JSONObject) exec(cmdPattern);
if (res == null) {
return null;
}
Integer code = res.getInteger("code");
if (code == null) {
return null;
}
if (code.equals(new Integer(0))) {
return res;
} else {
logger.warn("get agent data error with error code : {}, msg: {}, {}", code, res.get("msg"),
res.get("data"));
return null;
}
}

@Override
public AgentCmd buildCmd(String cmdPattern, Map<String, String> args) {
Map<String, String> map = new HashMap<String, String>(args);
return new AgentCmd(cmdPattern, map);
}

@Override
public int close() {
try {
if (client != null){
client.close();
}
} catch (IOException e) {
logger.error("error closing http connection", e);
}
connected = false;

super.close();
return 0;
}

@Override
public boolean testWithConnected(String cmdString, String resStart) {
connected = false;
try {
JSONObject res = null;
try {
res = (JSONObject) exec(new AgentCmd("test_conn", new HashMap<String, String>()));
} catch (SimoConnectionException e) {
logger.error("error executing cmd in http connection", e);
}
if (res != null) {
Long code = res.getLong("code");
if (code.equals(-777L)) {
connected = false;
} else {
connected = true;
}
}
} catch (Exception e) {
logger.warn("{}", e);
connected = false;
}
logger.info("http connection test result: {}", connected);
return connected;
}
}






说明:1. 黄色部分为表单传输和body 传输同时进行,
   2. 灰色部分为表单传输
3. 通过实验证明灰色部分和黑色部分不能同时进行。如果要达到两种效果用1
posted @ 2021-02-26 15:34  dousil  阅读(1153)  评论(0编辑  收藏  举报