java连接http代码如下:

 

import org.json.JSONObject;

import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.*;

public class HTTP_POST {
    URL realUrl;
    HttpURLConnection connection;
    /*
     * basic_conf() 封装http请求头,如果需要添加或者更改头文件,都在这里设置
     *
     * */
    public void basic_conf(String cookie){ // cookie 用来表示,是否还有需要修改的请求头参数
        try {
            this.connection= (HttpURLConnection) this.realUrl.openConnection();
            this.connection.setUseCaches(false); //不使用缓存
            this.connection.setInstanceFollowRedirects(false);
            //connection.setConnectTimeout(30000);
            //connection.setReadTimeout(30000);
            this.connection.setRequestProperty("Proxy-Connection","keep-alive");
            this.connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded; charset=GBK"); //设置提交格式
            // connection.setRequestProperty("Cookie","JSESSIONID=73415D3487B09EAE077C749B3E6734D4");
            //connection.setRequestProperty("X-Requested-With","XMLHttpRequest");
            this.connection.setRequestProperty("User-Agent","Apache-HttpClient/4.5.5 (Java/1.8.0_152)");
            //头文件添加、修改
            if(cookie != null){
                JSONObject j = new JSONObject(cookie);
                Iterator iterator = j.keys();
                while(iterator.hasNext()){
                    String key = (String) iterator.next();
                    this.connection.setRequestProperty(key,j.getString(key));
                }
            }

        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }

    public String post(String url,String j,String param) { //带请求头参数,如cookie 的post请求
        int response=0;
        StringBuffer sb=new StringBuffer();
        try{
            this.realUrl=new URL(url);
            basic_conf(j);
            this.connection.setRequestMethod("POST"); // 表示请求方法
            this.connection.setDoOutput(true);  //dooutput 和doinput 是post必须带的
            this.connection.setDoInput(true);this.connection.setInstanceFollowRedirects(false);
            this.connection.connect(); //建立连接
            OutputStream outputStream= this.connection.getOutputStream();
            StringBuffer buffer=new StringBuffer();
            buffer.append(param);
            outputStream.write(param.getBytes()); //将请求体转换成输出流
            outputStream.flush(); //将输出流刷新出去
            outputStream.close();
            response= this.connection.getResponseCode(); //等待获取响应码
            if(response == HttpURLConnection.HTTP_OK)
            {
                InputStream inputStream= this.connection.getInputStream();
                int len = 0 ;
                byte[] bys = new byte[1024];

                while ((len = inputStream.read(bys)) != -1) {
                    sb.append(new String(bys,0,len));
                }
                inputStream.close();
            }
            this.connection.disconnect();
            // System.out.println(sb.toString());

        }catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return response+"....返回内容:"+sb.toString();
    }

    public String post(String url,byte[] param) { //不带请求头修改的 post请求
        int response=0;
        StringBuffer sb=new StringBuffer();
        try{
            this.realUrl=new URL(url);
            basic_conf(null);
            this.connection.setRequestMethod("POST");
            this.connection.setDoOutput(true);
            this.connection.setDoInput(true);
            this.connection.setUseCaches(false);
            this.connection.setInstanceFollowRedirects(false);
            this.connection.connect();

            OutputStream outputStream= this.connection.getOutputStream();
           outputStream.write(param);
           outputStream.flush();
          outputStream.close();
            response= this.connection.getResponseCode();
            if(response == HttpURLConnection.HTTP_OK)
            {
                InputStream inputStream= this.connection.getInputStream();
                int len = 0 ;
                byte[] bys = new byte[1024];

                while ((len = inputStream.read(bys)) != -1) {
                    sb.append(new String(bys,0,len));
                }
                inputStream.close();
            }
            this.connection.disconnect();
            // System.out.println(sb.toString());

        }catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return response+"....返回内容:"+sb.toString();
    }

    public  String get(String url) { //get请求
        int response=0;
        StringBuffer sb=new StringBuffer();
        try {
            this.realUrl = new URL(url);
            // 打开和URL之间的连接
            basic_conf(null);
            this.connection.setUseCaches(false);
            this.connection.setInstanceFollowRedirects(false);
            this.connection.connect();
            response= this.connection.getResponseCode();
            if(response == HttpURLConnection.HTTP_OK)
            {
                InputStream inputStream= this.connection.getInputStream();
                int len = 0 ;
                byte[] bys = new byte[1024];

                while ((len = inputStream.read(bys)) != -1) {
                    sb.append(new String(bys,0,len));
                }
                inputStream.close();
            }
            this.connection.disconnect();
            // System.out.println(sb.toString());

        }catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return response+"....返回内容:"+sb.toString();
    }

    public  String get(String url,String cookie) { // 带修改请求头参数  get请求
        int response=0;
        StringBuffer sb=new StringBuffer();
        try {
            this.realUrl = new URL(url);
            // 打开和URL之间的连接
            basic_conf(cookie);
            this.connection.setUseCaches(false);
            this.connection.setInstanceFollowRedirects(false);
            this.connection.connect();
            response= this.connection.getResponseCode();
            if(response == HttpURLConnection.HTTP_OK)
            {
                InputStream inputStream= this.connection.getInputStream();
                int len = 0 ;
                byte[] bys = new byte[1024];

                while ((len = inputStream.read(bys)) != -1) {
                    sb.append(new String(bys,0,len));
                }
                inputStream.close();
            }
            this.connection.disconnect();
            // System.out.println(sb.toString());

        }catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return response+"....返回内容:"+sb.toString();
    }


    public static void main(String[] args) throws Exception {

        //System.setProperty("http.proxyHost", "127.0.0.1");
       // System.setProperty("https.proxyHost", "127.0.0.1");
       // System.setProperty("http.proxyPort", "8888");
       // System.setProperty("https.proxyPort", "8888");

       StringBuffer sb=new StringBuffer();

String param="APPID=hu1TjSmrQNtO9jm1kxzVwP1zOJc%3D&AuthToken=PEF1dGhUb2tlbj48UmVzdWx0VHlwZT5ZPC9SZXN1bHRUeXBlPjxBdXRoRGF0YT5YNzM4eFRiTEVGOGhxT2hQZklqTnZKcGd6YjgxU2crVDNEY2RObFNQQnlabXJSZzJuUktIdEg2YVJUN0J3cWJ0QnZBS2xOZkFmcXZlZWthWUdldWgzRlkvMmJxdEFta3F1WTBsTGdLWVVUWVcxZ1pBKytkZU55QWYzN2JML0NMZ3VySVpmZ1lKOUNjbUJIOGVhS2JoWWxtMGg0RzFwNzVGNWR5ejgzbmx0T2JSRkxVckNyNzh3bTg3MHpMVjV0MHBBZE5sNnVvVEJLU3JvYXpIcTBJK2EvdVJPeTAxWkpvM1FrekdhL2FObzk4am5TaG8zNEZQSG0wNDNQZXpnRjZwZ0V4Z1dTRGpOeE0vQ01FQmt3U05lZlVGVFpRL3VrQzVxRVVpKzhVamlKbnRIZkxMNVNLV2xEaXN3MzBvZjZCWWpqR3ZLWGF2TUI4Ky8ySjhCT2pGanh2V21hSUh4Uys2WHJyOVFrR0VMNkpxTmtlVHJhMURZV2gxVkM2dXZVZm9KYjdtdnFBWlRLVUR4dUhlVjVQSVN0NlhrU04wcTJaYm91eGtXWEZsdGdSa1dyNnpzUGR3TjlzVlZnZXI2SnJtRGgyTkZaakpFNHhzK2hhdzZUNXRhTGd4VVMrTXVRK3BuRk85dkNRZWtQRkZxTkpmUDBtUS9wZVkyNEUrc1FkaDF4MEp4bjdmb1NHbzY4RDZ0VXJjaGNrSERrejREOGxVK0FoRDd0MGZpMkVSQU9HOVlwdXBNM3hVWFNmaG9DcHRmd05zNUJUY1pkSHFqQlFTaVVTV2Qzd1BKTjZRMzRlWjNzZWJrN091dXl3ODl1RHJqdThnZGN0RzlJRG1VWE8xdGVJM3hybUhpcWM9PC9BdXRoRGF0YT48QXV0aE5hbWU%2BTUJBTktfT05FTkVUPC9BdXRoTmFtZT48QXV0aFNpZ25hdHVyZT5qcitUZk50SHViamRHWjd6SnpCdENTL3Zyb3lmcSsraU41SURLekw5WjZSR24zcmVBcENILzQvWkhxQ1NQcnRZSzRqZUNCSzd1ZG1qZXN6Q1Y4bGFsaTNNd0FtWUNrcmpKdzBzeTcrczVIeGQ3RjFWMGo2K2NTbkxFVktCVVpNaHlZUjFJR1pWZ1VYdng1OTg1dHpNRWRSejloMVAyOFNlcWJqYVlKbGs1eG89PC9BdXRoU2lnbmF0dXJlPjxUaW1hc3RhbXA%2BMjAyMDExMTMxMTE4MjA8L1RpbWFzdGFtcD48L0F1dGhUb2tlbj4%3D";

        HTTP_POST a=new HTTP_POST();
    //需要编码问题,就想到发byte[] 就行,保证没错
        String xx=a.post("http://XXXXXXX/login/loginclient",param.getBytes(StandardCharsets.UTF_8));
        //String xx=a.get("http://XXXXXXXXX?method=queryP2pPaymentAppointmentInfoInit");
        System.out.println(xx);
    }

}

 

以上的HttpURLConnection是比较古董的是否方式,也可以称之为比较底层的操作。其实就是在建立http通道后,将请求体以字节流的方式进行传输。

 

posted on 2018-11-22 17:41  进_进  阅读(916)  评论(0)    收藏  举报