java httpclient form_java 编写http连接,以httpclient 方式,(推荐)。以及对multipart/form-data 的请求体的编写方式讲解...

importjava.io.ByteArrayInputStream;importjava.io.ByteArrayOutputStream;importjava.io.UnsupportedEncodingException;importjava.net.URLDecoder;importjava.net.URLEncoder;importjava.nio.charset.Charset;importjava.nio.charset.StandardCharsets;importjava.util.HashMap;importjava.util.zip.GZIPInputStream;importorg.apache.http.Header;importorg.apache.http.HttpEntity;importorg.apache.http.HttpResponse;importorg.apache.http.client.methods.HttpGet;importorg.apache.http.client.methods.HttpPost;importorg.apache.http.entity.ByteArrayEntity;importorg.apache.http.entity.ContentType;importorg.apache.http.entity.StringEntity;import org.apache.http.impl.client.*;public classhttp {private String con_type="UTF-8";public void basic_conf(HttpPost httpPost,HashMap headers){ //为post 生成默认的请求头参数,但是传递的参数是:map视图格式

httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

httpPost.setHeader("Proxy-Connection", "keep-alive");//httpPost.setHeader("Accept", "application/json, text/javascript, */*");//httpPost.setHeader("Accept-Encoding","gzip, deflate");

if (headers != null) {for(String key : headers.keySet()) {

httpPost.setHeader(key, headers.get(key));

}

}

}public void basic_conf(HttpGet httpGet,HashMap headers){ //为get请求传递默认的请求头参数

httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

httpGet.setHeader("Proxy-Connection", "keep-alive");

httpGet.setHeader("Accept", "application/json, text/javascript, */*");//httpPost.setHeader("Accept-Encoding","gzip, deflate");

if (headers != null) {for(String key : headers.keySet()) {

httpGet.setHeader(key, headers.get(key));

}

}

}public String content_type(String s){ //为了判断返回的响应头,contentType是否包含了别的编码要求

String result=null;if(s.toLowerCase().contains("gbk")){

result="GBK";

}else if(s.toLowerCase().contains("utf-8")){

result="UTF-8";

}else if(s.toLowerCase().contains("gb2312")){

result="GB2312";

}else if(s.toLowerCase().contains("iso-8859-1")){

result="ISO-8859-1";

}returnresult;

}public String post(String url, HashMap headers,String param) throwsException {

HttpPost httpPost= newHttpPost(url);

basic_conf(httpPost,headers);

StringEntity entity= newStringEntity(param,StandardCharsets.UTF_8);

httpPost.setEntity(entity);

HttpResponse httpResponse= new DefaultHttpClient().execute(httpPost); //发送请求

intstatusCode;

statusCode= httpResponse.getStatusLine().getStatusCode(); //获取响应码

if (statusCode == 200) { //判断请求是不是200

HttpEntity res=httpResponse.getEntity();if(res.getContentType()!=null) {

con_type= res.getContentType().getValue(); //获取响应报文头的编码格式

}

ByteArrayOutputStream out= newByteArrayOutputStream();

httpResponse.getEntity().writeTo(out);//将获取的报文写入数组流中

Header gce=res.getContentEncoding(); //报文是否进行了压缩

if(gce!=null){ //判断是不是压缩了的

if(gce.getValue().toLowerCase().contains("gzip")) {

ByteArrayInputStream in= newByteArrayInputStream(out.toByteArray());//将响应报文写入输出流

try{

GZIPInputStream ungzip= newGZIPInputStream(in);byte[] buffer = new byte[256];intn;while ((n = ungzip.read(buffer)) >= 0) {

out.write(buffer,0, n);

}

String gbkstr= newString(out.toByteArray(), content_type(con_type));returngbkstr;

}catch(Exception e) {

e.printStackTrace();

}

}

}else{ //如果不需要压缩,直接将字节流转成字节数组,然后由字节数组根据一定的编码格式,最后生成字符串

String gbkstr= newString(out.toByteArray(), content_type(con_type));returngbkstr;

}

}return "响应码为:"+statusCode;

}public String post(String url, HashMap headers,byte[] be) throwsException {

HttpPost httpPost= newHttpPost(url);

basic_conf(httpPost,headers);

httpPost.setEntity(newByteArrayEntity(be));

HttpResponse httpResponse= new DefaultHttpClient().execute(httpPost); //发送请求

intstatusCode;

statusCode= httpResponse.getStatusLine().getStatusCode(); //获取响应码

if (statusCode == 200) { //判断请求是不是200

HttpEntity res=httpResponse.getEntity();if(res.getContentType() !=null){

con_type= res.getContentType().getValue(); //获取响应报文头的编码格式

}

ByteArrayOutputStream out= newByteArrayOutputStream();

httpResponse.getEntity().writeTo(out);//将获取的报文写入数组流中

Header gce=res.getContentEncoding(); //报文是否进行了压缩

if(gce!=null){ //判断是不是压缩了的

if(gce.getValue().toLowerCase().contains("gzip")) {

ByteArrayInputStream in= newByteArrayInputStream(out.toByteArray());//将响应报文写入输出流

try{

GZIPInputStream ungzip= newGZIPInputStream(in);byte[] buffer = new byte[256];intn;while ((n = ungzip.read(buffer)) >= 0) {

out.write(buffer,0, n);

}

String gbkstr= newString(out.toByteArray(), content_type(con_type));returngbkstr;

}catch(Exception e) {

e.printStackTrace();

}

}

}else{ //如果不需要压缩,直接将字节流转成字节数组,然后由字节数组根据一定的编码格式,最后生成字符串

String gbkstr= newString(out.toByteArray(), content_type(con_type));returngbkstr;

}

}return "响应码为:"+statusCode;

}public String post(String url,byte[] param) throwsException {

HttpPost httpPost= newHttpPost(url);

basic_conf(httpPost,null);

httpPost.setEntity(newByteArrayEntity(param));

HttpResponse httpResponse= newDefaultHttpClient().execute(httpPost);intstatusCode;

statusCode=httpResponse.getStatusLine().getStatusCode();if ((statusCode = httpResponse.getStatusLine().getStatusCode()) == 200) { //判断请求是不是200

HttpEntity res=httpResponse.getEntity();if(res.getContentType()!=null) {

con_type= res.getContentType().getValue(); //获取响应报文头的编码格式

}

ByteArrayOutputStream out= newByteArrayOutputStream();

httpResponse.getEntity().writeTo(out);//将获取的报文写入数组流中

Header gce=res.getContentEncoding(); //报文是否进行了压缩

if(gce!=null){ //判断是不是压缩了的

if(gce.getValue().toLowerCase().contains("gzip")) {

ByteArrayInputStream in= newByteArrayInputStream(out.toByteArray());//将响应报文写入输出流

try{

GZIPInputStream ungzip= newGZIPInputStream(in);byte[] buffer = new byte[256];intn;while ((n = ungzip.read(buffer)) >= 0) {

out.write(buffer,0, n);

}

String gbkstr= newString(out.toByteArray(), content_type(con_type));returngbkstr;

}catch(Exception e) {

e.printStackTrace();

}

}

}else{

String gbkstr= newString(out.toByteArray(), content_type(con_type));returngbkstr;

}

}return "响应码为:"+statusCode;

}public String get(String url, HashMap headers) throwsException {

HttpGet httpGet= newHttpGet(url);

basic_conf(httpGet,headers);

HttpResponse httpResponse= newDefaultHttpClient().execute(httpGet);intstatusCode;

statusCode=httpResponse.getStatusLine().getStatusCode();if ((statusCode = httpResponse.getStatusLine().getStatusCode()) == 200) { //判断请求是不是200

HttpEntity res=httpResponse.getEntity();

String con_type=res.getContentType().getValue(); //获取响应报文头的编码格式

ByteArrayOutputStream out = newByteArrayOutputStream();

httpResponse.getEntity().writeTo(out);//将获取的报文写入数组流中

Header gce=res.getContentEncoding(); //报文是否进行了压缩

if(gce!=null){ //判断是不是压缩了的

if(gce.getValue().toLowerCase().contains("gzip")) {

ByteArrayInputStream in= newByteArrayInputStream(out.toByteArray());//将响应报文写入输出流

try{

GZIPInputStream ungzip= newGZIPInputStream(in);byte[] buffer = new byte[256];intn;while ((n = ungzip.read(buffer)) >= 0) {

out.write(buffer,0, n);

}

String gbkstr= newString(out.toByteArray(), content_type(con_type));returngbkstr;

}catch(Exception e) {

e.printStackTrace();

}

}

}else{

String gbkstr= newString(out.toByteArray(), content_type(con_type));returngbkstr;

}

}return "响应码为:"+statusCode;

}public String get(String url) throwsException {

HttpGet httpGet= newHttpGet(url);

basic_conf(httpGet,null);

HttpResponse httpResponse= newDefaultHttpClient().execute(httpGet);intstatusCode;

statusCode=httpResponse.getStatusLine().getStatusCode();if ((statusCode = httpResponse.getStatusLine().getStatusCode()) == 200) { //判断请求是不是200

HttpEntity res=httpResponse.getEntity();

String con_type=res.getContentType().getValue(); //获取响应报文头的编码格式

ByteArrayOutputStream out = newByteArrayOutputStream();

httpResponse.getEntity().writeTo(out);//将获取的报文写入数组流中

Header gce=res.getContentEncoding(); //报文是否进行了压缩

if(gce!=null){ //判断是不是压缩了的

if(gce.getValue().toLowerCase().contains("gzip")) {

ByteArrayInputStream in= newByteArrayInputStream(out.toByteArray());//将响应报文写入输出流

try{

GZIPInputStream ungzip= newGZIPInputStream(in);byte[] buffer = new byte[256];intn;while ((n = ungzip.read(buffer)) >= 0) {

out.write(buffer,0, n);

}

String gbkstr= newString(out.toByteArray(), content_type(con_type));returngbkstr;

}catch(Exception e) {

e.printStackTrace();

}

}

}else{

String gbkstr= newString(out.toByteArray(), content_type(con_type));returngbkstr;

}

}return "响应码为:"+statusCode;

}/***@paramargs*/

public static void main(String[] args) throwsUnsupportedEncodingException {//System.setProperty("http.proxyHost", "127.0.0.1");//System.setProperty("https.proxyHost", "127.0.0.1");//System.setProperty("http.proxyPort", "8889");//System.setProperty("https.proxyPort", "8889");//TODO Auto-generated method stub

http x=newhttp();

HashMap map=new HashMap();//map.put("Cookie","cod=3000.50000; JSESSIONID=B612C9CF4BE6E10A220EDE8E91D754B4; csd=50008");//为了请求头传递参数//map.put("Content-Type","application/object;charset=UTF-8");

map.put("Content-Type","application/object;charset=UTF-8");//map.put("Upgrade-Insecure-Requests","1");//map.put("Cache-Control","max-age=0");

String json = "{\n" +

" \"SYSCOD\": \"1001\",\n" +

" \"INSTIN\": \"AA4360520082230951\",\n" +

" \"SFKDAT\": \"20200822\",\n" +

" \"FUNDID\": \"JK950002\",\n" +

" \"SECCOD\": \"111710160\",\n" +

" \"SECMAR\": \"3\",\n" +

" \"BUSINE\": \"1\",\n" +

" \"FIRSTD\": \"4\",\n" +

" \"LASTDE\": \"\",\n" +

" \"COMNAM\": \"test\",\n" +

" \"ENSHKJ\": \"2000\",\n" +

" \"ENAMOU\": \"20000\",\n" +

" \"LASTDA\": \"\",\n" +

" \"BUSTYP\": \"1004\",\n" +

" \"ZQTZFL\": \"\",\n" +

" \"CJONBR\": \"TG2008220008252367\",\n" +

" \"QTCONT\": \"20200822\"\n" +

"}";

String param= "0281VLMONJSON JSON " +("0000000000000000000"+json.length()).substring(String.valueOf(json.length()).length()) + "VL$BSVRHEAD$RQTYPE000000000000000000";try{byte[] bytes=param.getBytes(StandardCharsets.UTF_8);//这个是为了拼接byte[]

ByteArrayOutputStream bos = newByteArrayOutputStream();

bos.write(bytes);

String xx;

System.out.println("发送的数据是:"+newString ( bos.toByteArray(),StandardCharsets.UTF_8));//改为发送byte[]。避免了转码问题,

xx = x.post("http://monconfig.paas.cmbchina.cn/tbmonitor/ccsPacket/MONSQRES",map, bos.toByteArray());//如果需要用到jmeter中,那么就需要将byte[] 转为字符串就行,注意编码格式就行。

xx = x.post("http:/XXXXXX/tbmonitor/ccsPacket/MONSQRES", map, new String(bos.toByteArray(), "utf-8"));

System.out.println("返回结果:"+xx);

}catch(Exception e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}

}


版权声明:本文为weixin_36329425原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。