URLConnection 和 HttpClients 发送请求范例【原】

笔记,未完全标准.

java.net.URLConnection

package test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;


public class Test {
    
    public static void main(String[] args) throws Exception{
        try {
            //String info=HttpTool.sendRequestData("searchArg=宝马740", "http://localhost:8080/vhl/VhlSearch.act", new Long(300000));
            String info=invoke("vhlName=大众","http://localhost:8080/vhl/vhlSearch.html");
            System.out.println("接收到的车辆信息:"+info);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
private static String invoke(String param, String url) throws Exception {
        
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("vhlsinfo", "<?xml version="1.0" encoding="UTF-8" ?> <PACKET><TOTAL>哈哈</TOTAL> <VHL_LIST /></PACKET>");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(),"UTF-8"));//请求编码设置
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));//返回编码设置
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

}

.

org.apache.http.impl.client.HttpClients

package com.testdemo.validate.tool;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.EntityBuilder;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class ESB {
    
    public static String invoke(String paramStr,String url,String systemName) throws Exception{
        CloseableHttpClient httpclient = null;
        String response = null;
        httpclient = HttpClients.custom().build();
        HttpPost httppost = new HttpPost(url);
        HttpEntity reqEntity = EntityBuilder.create()
        .setContentType(ContentType.APPLICATION_JSON)
        .setContentEncoding("UTF-8")
        .setText(paramStr)
        .build();

        httppost.setEntity(reqEntity);
        httppost.setHeader("userName", systemName);//在head中设置属性,后台服务端提取系统名
        
        try {
            response = httpclient.execute(httppost,
                    new ResponseHandler<String>() {
                        // 处理响应
                        @Override
                        public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
                            String responseJson = null;
                            HttpEntity entity = null;
                            int status = response.getStatusLine().getStatusCode();
                            if (status >= 200 && status < 300) {
                                entity = response.getEntity();
                                if (entity != null) {
                                    String sentity = EntityUtils.toString(entity, "UTF-8");
                                    if (sentity == null|| sentity.trim().length() == 0)
                                        return null;
                                    responseJson = sentity;
                                    //write(responseJson);
                                } else {
                                    responseJson = response.getStatusLine().getReasonPhrase()+ "  返回的结果为空!";
                                }
                            } else {
                                responseJson = response.getStatusLine().toString();
                            }
                            //System.out.println(responseJson);
                            return responseJson;
                        }
                    });

        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            // 5. 释放连接
            httppost.releaseConnection();
            httpclient.close();
        }
        return response;
    }
    
    public static void main(String[] args) throws Exception{
        String systemName = "echannel";
        System.out.print(invoke("VHL_NAME=马自达&RET_TYPE=json","http://192.168.1.2:8012/vhl/vhlSearch.do",null));
//        System.out.print(invoke("VHL_NAME=马自达&RET_TYPE=json","http://localhost:8080/vhl/vhlSearch.do",systemName));
        
    }

}
原文地址:https://www.cnblogs.com/whatlonelytear/p/5056008.html