POST GET 工具类

/**
 * post   string
 * */
public  String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
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);
conn.setConnectTimeout(60000);
conn.setReadTimeout(60000);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
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;
}

/**
* post   JSON
*/
public static String postJSON(Mapmap,String url) {
JSONObject  obj = JSONObject.fromObject(map);
StringBuilder sb = new StringBuilder();
try {
// 请求参数 
String data = obj.toString();
SslContextUtils sslContextUtils = new SslContextUtils();
// 请求地址
URL Url = new URL(url);
HttpURLConnection httpConn = (HttpURLConnection) Url.openConnection();
if (httpConn instanceof HttpsURLConnection) {
sslContextUtils.initHttpsConnect((HttpsURLConnection) httpConn);
}
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
httpConn.setRequestProperty("Content-type", "text/json");
httpConn.setConnectTimeout(60000);
httpConn.setReadTimeout(60000);
// 发送请求
httpConn.getOutputStream().write(data.getBytes("utf-8"));
httpConn.getOutputStream().flush();
httpConn.getOutputStream().close();
// 获取输入流
BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(),"utf-8"));
char[] buf = new char[1024];
int length = 0;
while ((length = reader.read(buf)) > 0) {
sb.append(buf, 0, length);
}
// 响应参数
System.out.println(sb);
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}


public static class SslContextUtils {
private TrustManager trustAllManager;
SSLContext sslcontext;
HostnameVerifier allHostsValid;


public SslContextUtils() {
initContext();
}


private void initContext() {
trustAllManager = new X509TrustManager() {


public void checkClientTrusted(
java.security.cert.X509Certificate[] arg0, String arg1) {
}


public void checkServerTrusted(
java.security.cert.X509Certificate[] arg0, String arg1) {
}


public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}


};
try {
sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null, new TrustManager[] { trustAllManager },
null);
} catch (Exception e) {
e.printStackTrace();
}
allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
}


public void initHttpsConnect(HttpsURLConnection httpsConn) {
httpsConn.setSSLSocketFactory(sslcontext.getSocketFactory());
httpsConn.setHostnameVerifier(allHostsValid);
}
}

/**
* POST map
*/
public String doPost(String url, Map parameterMap, String charSet) throws Exception {



StringBuffer parameterBuffer = new StringBuffer();
if (parameterMap != null) {
Iterator iterator = parameterMap.keySet().iterator();
String key = null;
String value = null;
while (iterator.hasNext()) {
key = (String) iterator.next();
if (parameterMap.get(key) != null) {
value = (String) parameterMap.get(key);
} else {
value = "";
}


parameterBuffer.append(key).append("=").append(value);
if (iterator.hasNext()) {
parameterBuffer.append("&");
}
}
}


URL localURL = new URL(url);


URLConnection connection = openConnection(localURL);
HttpURLConnection httpURLConnection = (HttpURLConnection) connection;


httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Accept-Charset", charset);
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpURLConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0");
httpURLConnection.setRequestProperty("Content-Length", String.valueOf(parameterBuffer.length()));
httpURLConnection.setConnectTimeout(30000);
httpURLConnection.setReadTimeout(30000);


OutputStream outputStream = null;
OutputStreamWriter outputStreamWriter = null;
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader reader = null;


StringBuffer resultBuffer = new StringBuffer();
String tempLine = null;


try {
outputStream = httpURLConnection.getOutputStream();
outputStreamWriter = new OutputStreamWriter(outputStream, charSet);


outputStreamWriter.write(parameterBuffer.toString());
outputStreamWriter.flush();


if (httpURLConnection.getResponseCode() >= 300) {
throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
}


inputStream = httpURLConnection.getInputStream();
inputStreamReader = new InputStreamReader(inputStream, charSet);
reader = new BufferedReader(inputStreamReader);


while ((tempLine = reader.readLine()) != null) {
resultBuffer.append(tempLine);
}


} finally {


if (outputStreamWriter != null) {
outputStreamWriter.close();
}


if (outputStream != null) {
outputStream.close();
}


if (reader != null) {
reader.close();
}


if (inputStreamReader != null) {
inputStreamReader.close();
}


if (inputStream != null) {
inputStream.close();
}


}


return resultBuffer.toString();
}



/**
     * HTTP GET请求
     * 
     * @param url
     * @param params
     * @param encoding
     * @return
     */
    public static String doGet(String url, String value) {
    String encoding="utf-8";
        HttpClient httpClient = new DefaultHttpClient();
        String body = null;
        HttpEntity entity = null;
        try {
        URL strUrl = new URL(url);
        URI uri = new URI(strUrl.getProtocol(), strUrl.getHost(), strUrl.getPath(), strUrl.getQuery(), null);
            HttpGet httpget = new HttpGet(uri);
            httpget.setHeader("Content-Type","application/json;charset=utf-8");
            /*
             * 设置参数
             */
            httpget.setURI(new URI(httpget.getURI().toString() + "?" + value));
            /*
             * 发送请求
             */
            org.apache.http.HttpResponse httpresponse = httpClient.execute(httpget);
            /*
             * 获取返回数据
             */
            entity = httpresponse.getEntity();
            body = EntityUtils.toString(entity, encoding);
       
        } catch (Exception e) {
        //logger.info("随行付请求异常,异常详情:{}", e);
        e.printStackTrace();
        } 
        return body;
    }
    

/**
     * HTTP POST请求
     * 
     * @param url
     * @param params
     * @param encoding
     * @return
     */

    public static String doPost(String url, String json) {
    String body = null;
         HttpEntity entity1 = null;
         HttpClient httpClient = new DefaultHttpClient();
try{
HttpPost post = new HttpPost(url);
StringEntity entity = new StringEntity(json, "UTF-8");
post.setEntity(entity);
post.setHeader("Content-Type", "application/json;charset=utf-8");
//logger.info("post:" + post);


       org.apache.http.HttpResponse httpresponse = httpClient.execute(post);
       
       entity1 = httpresponse.getEntity();
       body = EntityUtils.toString(entity1, "UTF-8");
       System.out.println(body);
}catch (Exception ex) {
ex.printStackTrace();
return "exception";
} finally {
           try {
               EntityUtils.consume(entity1);
           } catch (IOException e) {
           }
           httpClient.getConnectionManager().shutdown();
       }
return body;
}

/*post json*/

  public String sendPost(String url,String Params)throws IOException{
         OutputStreamWriter out = null;
         BufferedReader reader = null;
         String response="";
         try {
             URL httpUrl = null; //HTTP URL类 用这个类来创建连接
             //创建URL
             httpUrl = new URL(url);
             //建立连接
             HttpURLConnection conn = (HttpURLConnection) 	     	     	   
             httpUrl.openConnection();
             conn.setRequestMethod("POST");
             conn.setRequestProperty("Content-Type", "application/json");
             conn.setRequestProperty("connection", "keep-alive");
             conn.setUseCaches(false);//设置不要缓存
             conn.setInstanceFollowRedirects(true);
             conn.setDoOutput(true);
             conn.setDoInput(true);
             conn.connect();
             //POST请求
             out = new OutputStreamWriter(
                     conn.getOutputStream());
             out.write(Params);
             out.flush();
             //读取响应
             reader = new BufferedReader(new InputStreamReader(
                     conn.getInputStream()));
             String lines;
             while ((lines = reader.readLine()) != null) {
                 lines = new String(lines.getBytes(), "utf-8");
                 response+=lines;
             }
            reader.close();
             // 断开连接
             conn.disconnect();
            System.err.out("同步响应报文:"+response)
         } catch (Exception e) {
         e.printStackTrace();
         }
         //使用finally块来关闭输出流、输入流
         finally{
        try{
             if(out!=null){
                 out.close();
             }
             if(reader!=null){
                 reader.close();
             }
         }
         catch(IOException ex){
             ex.printStackTrace();
         }
     }
         return response;
     }
}

 /**
       * post请求
       * @param url
       * @param json
       * @return
       */
      public static JSONObject doPost(String url,JSONObject json){
          DefaultHttpClient client = new DefaultHttpClient();
          HttpPost post = new HttpPost(url);
          JSONObject response = null;
          try {
              StringEntity s = new StringEntity(json.toString());
              s.setContentEncoding("UTF-8");
              s.setContentType("application/json");//发送json数据需要设置contentType
              post.setEntity(s);
              HttpResponse res = client.execute(post);
              if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                  HttpEntity entity = res.getEntity();
                  String result = EntityUtils.toString(res.getEntity());// 返回json格式:
                  response = JSONObject.fromObject(result);
              }
          } catch (Exception e) {
              throw new RuntimeException(e);
          }
          return response;

      }


/*post   json*/

public static String  postJson (JSONObject  obj) throws Exception{

            // 创建url资源
            URL url = new URL("http://xxx.xxx.xxx.xxx");
            // 建立http连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 设置允许输出
            conn.setDoOutput(true);
            // 设置允许输入
            conn.setDoInput(true);
            // 设置不用缓存
            conn.setUseCaches(false);
            // 设置传递方式
            conn.setRequestMethod("POST");
            // 设置维持长连接
            conn.setRequestProperty("Connection", "Keep-Alive");
            // 设置文件字符集:
            conn.setRequestProperty("Charset", "UTF-8");
            //转换为字节数组
            byte[] data = (obj.toString()).getBytes();
            // 设置文件长度
            conn.setRequestProperty("Content-Length", String.valueOf(data.length));
            // 设置文件类型:
            conn.setRequestProperty("contentType", "application/json");


            // 开始连接请求
            conn.connect();
            OutputStream  out = conn.getOutputStream();     
            // 写入请求的字符串
            out.write((obj.toString()).getBytes());
            out.flush();
            out.close();
            System.err.println("post 请求状态码:"+conn.getResponseCode());
            // 请求返回的状态
            if (conn.getResponseCode() == 200) {
                System.out.println("连接成功");
                // 请求返回的数据
                InputStream in = conn.getInputStream();
                String a = null;
                
                byte[] data1 = new byte[in.available()];
                in.read(data1);
                // 转成字符串
                a = new String(data1);
                return a;
                
            } else {
                System.out.println("post 请求不成功");
                return null;
            }

    }

你可能感兴趣的:(POST GET 工具类)