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


java 编写http连接,以httpclient 方式。

第一步是需要导入包:

主要有以上几个包。

第二步:编写代码如下:

package test;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.zip.GZIPInputStream;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.*;


public class B {
    
    public void basic_conf(HttpPost httpPost,HashMap<String, String> 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<String, String> 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";
        }
        return result;
    }
    
    public  String post(String url, HashMap<String, String> headers,String param) throws Exception {
        HttpPost httpPost = new HttpPost(url);
        basic_conf(httpPost,headers);
         StringEntity entity = new StringEntity(param);
            httpPost.setEntity(entity);
        HttpResponse httpResponse = new DefaultHttpClient().execute(httpPost); //发送请求
        int statusCode;
        statusCode = httpResponse.getStatusLine().getStatusCode(); //获取响应码
        if (statusCode == 200) { //判断请求是不是200
            HttpEntity res=httpResponse.getEntity(); 
            String con_type=res.getContentType().getValue();  //获取响应报文头的编码格式
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            httpResponse.getEntity().writeTo(out);  //将获取的报文写入数组流中
             Header gce=res.getContentEncoding();   //报文是否进行了压缩
            if(gce!=null){  //判断是不是压缩了的
                if(gce.getValue().toLowerCase().contains("gzip")) {
                    ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
                      //将响应报文写入输出流
                    try {
                        GZIPInputStream ungzip = new GZIPInputStream(in);
                        byte[] buffer = new byte[256];
                        int n;
                        while ((n = ungzip.read(buffer)) >= 0) {
                            out.write(buffer, 0, n);
                        }
                        String  gbkstr= new String(out.toByteArray(), content_type(con_type));
                        return gbkstr;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                }else{ //如果不需要压缩,直接将字节流转成字节数组,然后由字节数组根据一定的编码格式,最后生成字符串
                      String  gbkstr= new String(out.toByteArray(), content_type(con_type));
                      return gbkstr;    
            }
        }
        return "响应码为:"+statusCode;
    }
    
    public  String post(String url,String param) throws Exception {
        HttpPost httpPost = new HttpPost(url);
        basic_conf(httpPost,null);
         StringEntity entity = new StringEntity(param);
            httpPost.setEntity(entity);
        HttpResponse httpResponse = new DefaultHttpClient().execute(httpPost);
        int statusCode;
        statusCode = httpResponse.getStatusLine().getStatusCode();
        if ((statusCode = httpResponse.getStatusLine().getStatusCode()) == 200) { //判断请求是不是200
            HttpEntity res=httpResponse.getEntity(); 
            String con_type=res.getContentType().getValue();  //获取响应报文头的编码格式
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            httpResponse.getEntity().writeTo(out);  //将获取的报文写入数组流中
             Header gce=res.getContentEncoding();   //报文是否进行了压缩
            if(gce!=null){  //判断是不是压缩了的
                if(gce.getValue().toLowerCase().contains("gzip")) {
                    ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
                      //将响应报文写入输出流
                    try {
                        GZIPInputStream ungzip = new GZIPInputStream(in);
                        byte[] buffer = new byte[256];
                        int n;
                        while ((n = ungzip.read(buffer)) >= 0) {
                            out.write(buffer, 0, n);
                        }
                        String  gbkstr= new String(out.toByteArray(), content_type(con_type));
                        return gbkstr;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                }else{
                      String  gbkstr= new String(out.toByteArray(), content_type(con_type));
                      return gbkstr;    
            }
        }
        return "响应码为:"+statusCode;
    }
    
    
    public  String get(String url, HashMap<String, String> headers) throws Exception {
        HttpGet httpGet = new HttpGet(url);
        basic_conf(httpGet,headers);
        HttpResponse httpResponse = new DefaultHttpClient().execute(httpGet);
        int statusCode;
        statusCode = httpResponse.getStatusLine().getStatusCode();
        if ((statusCode = httpResponse.getStatusLine().getStatusCode()) == 200) { //判断请求是不是200
            HttpEntity res=httpResponse.getEntity(); 
            String con_type=res.getContentType().getValue();  //获取响应报文头的编码格式
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            httpResponse.getEntity().writeTo(out);  //将获取的报文写入数组流中
             Header gce=res.getContentEncoding();   //报文是否进行了压缩
            if(gce!=null){  //判断是不是压缩了的
                if(gce.getValue().toLowerCase().contains("gzip")) {
                    ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
                      //将响应报文写入输出流
                    try {
                        GZIPInputStream ungzip = new GZIPInputStream(in);
                        byte[] buffer = new byte[256];
                        int n;
                        while ((n = ungzip.read(buffer)) >= 0) {
                            out.write(buffer, 0, n);
                        }
                        String  gbkstr= new String(out.toByteArray(), content_type(con_type));
                        return gbkstr;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                }else{
                      String  gbkstr= new String(out.toByteArray(), content_type(con_type));
                      return gbkstr;    
            }
        }
        return "响应码为:"+statusCode;
    }
    public  String get(String url) throws Exception {
        HttpGet httpGet = new HttpGet(url);
        basic_conf(httpGet,null);
        HttpResponse httpResponse = new DefaultHttpClient().execute(httpGet);
        int statusCode;
        statusCode = httpResponse.getStatusLine().getStatusCode();
        if ((statusCode = httpResponse.getStatusLine().getStatusCode()) == 200) { //判断请求是不是200
            HttpEntity res=httpResponse.getEntity(); 
            String con_type=res.getContentType().getValue();  //获取响应报文头的编码格式
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            httpResponse.getEntity().writeTo(out);  //将获取的报文写入数组流中
             Header gce=res.getContentEncoding();   //报文是否进行了压缩
            if(gce!=null){  //判断是不是压缩了的
                if(gce.getValue().toLowerCase().contains("gzip")) {
                    ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
                      //将响应报文写入输出流
                    try {
                        GZIPInputStream ungzip = new GZIPInputStream(in);
                        byte[] buffer = new byte[256];
                        int n;
                        while ((n = ungzip.read(buffer)) >= 0) {
                            out.write(buffer, 0, n);
                        }
                        String  gbkstr= new String(out.toByteArray(), content_type(con_type));
                        return gbkstr;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                }else{
                      String  gbkstr= new String(out.toByteArray(), content_type(con_type));
                      return gbkstr;    
            }
        }
        return "响应码为:"+statusCode;
    }
 
    /**
     * @param args
     */
    public static void main(String[] args) {
        
        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
        B x=new B();
        HashMap<String, String> map=new HashMap<String, String>();
        map.put("Cookie","cod=3000.50000; JSESSIONID=B612C9CF4BE6E10A220EDE8E91D754B4; csd=50008"); //为了请求头传递参数
        map.put("Content-Type","multipart/form-data; boundary=----WebKitFormBoundaryx43rZoh62YQipnV1");
        map.put("Upgrade-Insecure-Requests","1");
        map.put("Cache-Control","max-age=0");
        String j="platform_code=&charge_status=&mian_body=&charge_channel_code=&push_flag=&send_flag=&update_flag=&operate_name=&createTimeStart=2018-11-23&createTimeEnd=2018-11-30&updateTimeStart=&updateTimeEnd=&charge_type=1&single_no=&id_card=&bank_no=&loan_no=&currentPage=1&limit=10";try {
            String xx=x.post("http://sit1-credit.zhph.lan/p2pPaymentAppointmentAction.do",map,j);
            System.out.println(xx);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

 下面对一种特殊的传递格式进行讲解一下:

加入我将要传递的是一个文件,或者说,请求是以:multipart/form-data 方式。我们对请求报文的编写格式必须如下面的param变量。针对这种请求体,建议直接使用jmeter,来的更容易。当然测试时还有一种方式:跳过这个步骤。

public static void main(String[] args) {
        
        System.setProperty("http.proxyHost", "127.0.0.1"); //这个是为了将http请求通过fiddler进行监控起来
         System.setProperty("https.proxyHost", "127.0.0.1");
         System.setProperty("http.proxyPort", "8889");
         System.setProperty("https.proxyPort", "8889");
        // TODO Auto-generated method stub
        B x=new B();
        HashMap<String, String> map=new HashMap<String, String>();
        map.put("Cookie","cod=3000.50000; JSESSIONID=B612C9CF4BE6E10A220EDE8E91D754B4; csd=50008");
        map.put("Content-Type","multipart/form-data; boundary=----WebKitFormBoundaryx43rZoh62YQipnV1");
        map.put("Upgrade-Insecure-Requests","1");
        map.put("Cache-Control","max-age=0");
        //String j="platform_code=&charge_status=&mian_body=&charge_channel_code=&push_flag=&send_flag=&update_flag=&operate_name=&createTimeStart=2018-11-23&createTimeEnd=2018-11-30&updateTimeStart=&updateTimeEnd=&charge_type=1&single_no=&id_card=&bank_no=&loan_no=&currentPage=1&limit=10";
        String param="------WebKitFormBoundaryx43rZoh62YQipnV1"+"\r\n"
        +"Content-Disposition: form-data; name=\"org.apache.struts.taglib.html.TOKEN\""+"\r\n"
        +"\r\n"
        +"f996182ad68010c19ca47b58e09ec60e"+"\r\n"
        +"------WebKitFormBoundaryx43rZoh62YQipnV1"+"\r\n"
        +"Content-Disposition: form-data; name=\"org.apache.struts.taglib.html.TOKEN\""+"\r\n"
        +"\r\n"
        +"f996182ad68010c19ca47b58e09ec60e"+"\r\n"
        +"------WebKitFormBoundaryx43rZoh62YQipnV1"+"\r\n"
        +"Content-Disposition: form-data; name=\"loanContractNo\""+"\r\n"
        +"\r\n"
        +"\r\n"
        +"------WebKitFormBoundaryx43rZoh62YQipnV1"+"\r\n"
        +"Content-Disposition: form-data; name=\"loanName\""+"\r\n"
        +"\r\n"
        +"\r\n"
        +"------WebKitFormBoundaryx43rZoh62YQipnV1"+"\r\n"
        +"Content-Disposition: form-data; name=\"mainBody\""+"\r\n"
        +"\r\n"
        +"ZH"+"\r\n"
        +"------WebKitFormBoundaryx43rZoh62YQipnV1"+"\r\n"
        +"Content-Disposition: form-data; name=\"areaNo\""+"\r\n"
        +"\r\n"
        +"\r\n"
        +"------WebKitFormBoundaryx43rZoh62YQipnV1"+"\r\n"
        +"Content-Disposition: form-data; name=\"signAreaNo\""+"\r\n"
        +"\r\n"
        +"\r\n"
        +"------WebKitFormBoundaryx43rZoh62YQipnV1"+"v\n"
        +"Content-Disposition: form-data; name=\"newAreaNo\""+"\r\n"
        +"\r\n"
        +"\r\n"
        +"------WebKitFormBoundaryx43rZoh62YQipnV1"+"\r\n"
        +"Content-Disposition: form-data; name=\"monthPayDate\""+"\r\n"
        +"\r\n"
        +"\r\n"
        +"------WebKitFormBoundaryx43rZoh62YQipnV1"+"\r\n"
        +"Content-Disposition: form-data; name=\"productType\""+"\r\n"
        +"\r\n"              
        +"\r\n"
        +"------WebKitFormBoundaryx43rZoh62YQipnV1"+"\r\n"
        +"Content-Disposition: form-data; name=\"perPageCount\""+"\r\n"
        +"\r\n"
        +"15"+"\r\n"
        +"------WebKitFormBoundaryx43rZoh62YQipnV1"+"\r\n"
        +"Content-Disposition: form-data; name=\"turntovalue\""+"\r\n"
        +"\r\n"
        +"\r\n"
        +"------WebKitFormBoundaryx43rZoh62YQipnV1"+"\r\n"
        +"Content-Disposition: form-data; name=\"pageTurn\""+"\r\n"
        +"\r\n"
        +"YES"+"\r\n"
        +"------WebKitFormBoundaryx43rZoh62YQipnV1"+"\r\n"
        +"Content-Disposition: form-data; name=\"currPage\""+"\r\n"
        +"\r\n"      
        +"1"+"\r\n"
        +"------WebKitFormBoundaryx43rZoh62YQipnV1"+"\r\n"
        +"Content-Disposition: form-data; name=\"method\""+"\r\n"
        +"\r\n"
        +"queryP2pPaymentAppointmentInfo"+"\r\n"
        +"------WebKitFormBoundaryx43rZoh62YQipnV1"+"\r\n"
        +"Content-Disposition: form-data; name=\"selectlist\""+"\r\n"
        +"\r\n"
        +"#"+"\r\n"
        +"------WebKitFormBoundaryx43rZoh62YQipnV1"+"\r\n"
        +"Content-Disposition: form-data; name=\"drFileType\""+"\r\n"
        +"\r\n"
        +"\r\n"
        +"------WebKitFormBoundaryx43rZoh62YQipnV1"+"\r\n"
        +"Content-Disposition: form-data; name=\"uploadFile\"; filename=\"\""+"\r\n"
        +"Content-Type: application/octet-stream"+"\r\n"
        +"\r\n"
        +"\r\n"
        +"------WebKitFormBoundaryx43rZoh62YQipnV1"+"\r\n"
        +"Content-Disposition: form-data; name=\"dcFileType\""+"\r\n"
        +"\r\n"
        +"\r\n"
        +"------WebKitFormBoundaryx43rZoh62YQipnV1--"+"\r\n";
        
        try {
            String xx=x.post("http://sit1-credit.zhph.lan/p2pPaymentAppointmentAction.do",map,param);
            System.out.println(xx);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM