java调用http传json数据或字符串

来源:互联网 发布:鞋拔子脸 整形 知乎 编辑:程序博客网 时间:2024/04/29 16:34
package com.emm.util;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;


import net.sf.json.JSONObject;


public class HttpUtils {




 private  String firstCookie;
 public HttpUtils() {
 }


 public  String sendPostMessage(Map<String, String> params,
     String encode,String PATH) {


   StringBuffer stringBuffer = new StringBuffer();


   if (params != null && !params.isEmpty()) {
     for (Map.Entry<String, String> entry : params.entrySet()) {
       try {
         stringBuffer
             .append(entry.getKey())
             .append("=")
             .append(URLEncoder.encode(entry.getValue(), encode))
             .append("&");


       } catch (UnsupportedEncodingException e) {
         e.printStackTrace();
       }
     }
     stringBuffer.deleteCharAt(stringBuffer.length() - 1);
     System.out.println("-->>" + stringBuffer.toString());


     try {
    URL url = new URL(PATH);
       HttpURLConnection httpURLConnection = (HttpURLConnection) url
           .openConnection();
       httpURLConnection.setConnectTimeout(3000);
       httpURLConnection.setDoInput(true);// 从服务器获取数据
       httpURLConnection.setDoOutput(true);// 向服务器写入数据
       httpURLConnection.setRequestMethod("POST");


       byte[] mydata = stringBuffer.toString().getBytes();
       httpURLConnection.setRequestProperty("Content-Type",
           "application/x-www-form-urlencoded");
       httpURLConnection.setRequestProperty("Content-Lenth",
           String.valueOf(mydata.length));
       OutputStream outputStream = (OutputStream) httpURLConnection
           .getOutputStream();
       outputStream.write(mydata);
       int responseCode = httpURLConnection.getResponseCode();
       if (responseCode == 200) {


    String responseCookie = httpURLConnection.getHeaderField("Set-Cookie");// 取到所用的Cookie
    if (responseCookie != null) {
    firstCookie = responseCookie.substring(0, responseCookie.indexOf(";"));
    }
    return firstCookie.toString();


       }


     } catch (IOException e) {
       e.printStackTrace();
     }
   }


   return "";
 }


 public static String sendPostMessage2(Map<String, Object> params,
     String encode,String PATH,String firstCookie) throws UnsupportedEncodingException {


   if (params != null && !params.isEmpty()) {
    JSONObject json = JSONObject.fromObject(params);  
     System.out.println("-->>" + json.toString());


     try {
    URL  url = new URL(PATH);  
       HttpURLConnection httpURLConnection = (HttpURLConnection) url
           .openConnection();
       httpURLConnection.setConnectTimeout(3000);
       httpURLConnection.setDoInput(true);// 从服务器获取数据
       httpURLConnection.setDoOutput(true);// 向服务器写入数据


       byte[] mydata = json.toString().getBytes();
       httpURLConnection.setRequestProperty("Content-Type",
           "application/json");
       httpURLConnection.setRequestProperty("Cookie", firstCookie);
       httpURLConnection.setRequestMethod("POST");
       httpURLConnection.setUseCaches(true);
       OutputStream outputStream = (OutputStream) httpURLConnection
           .getOutputStream();
       outputStream.write(mydata);
       // 获得服务器响应的结果和状态码
       int responseCode = httpURLConnection.getResponseCode();
       if (responseCode == 200) {
         // 获得输入流,从服务器端获得数据
         InputStream inputStream = (InputStream) httpURLConnection
             .getInputStream();
         return (changeInputStream(inputStream, encode));
       }


     } catch (IOException e) {
       e.printStackTrace();
     }
   }


   return "";
 }  
 
 public static String changeInputStream(InputStream inputStream,
     String encode) {
   ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
   byte[] data = new byte[1024];
   int len = 0;
   String result = "";
   if (inputStream != null) {


     try {
       while ((len = inputStream.read(data)) != -1) {
         byteArrayOutputStream.write(data, 0, len);
       }
       result = new String(byteArrayOutputStream.toByteArray(), encode);


     } catch (IOException e) {
       e.printStackTrace();
     }


   }


   return result;
 }
 
public static  void ToDownLisences(int id,String result,String commonName) throws IOException{
 HttpURLConnection conn = null;
     InputStream inputStream = null;
     FileOutputStream fileOut = null;
     File file = null;
     String fileName=commonName+".p12"; 
     try {
      String path = Config.props.getProperty("downLoadCert")+id; 
           URL url = new URL(path);
           conn = (HttpURLConnection) url.openConnection();
           conn.setDoOutput(true);
           conn.setDoInput(true);
           conn.setUseCaches(false);
           conn.setRequestMethod("GET");
           conn.setRequestProperty("Cookie", result);
String filePath = Config.props.getProperty("downLoadPath"); 
File fp = new File(filePath);  
// 创建目录  
if (!fp.exists()) {  
   fp.mkdirs();// 目录不存在的情况下,创建目录。  
}

fileName = fileName.substring(fileName.lastIndexOf('/')+1);           
           inputStream = conn.getInputStream();
           if(inputStream!=null){
               file = new File(filePath+fileName);
           }
           //写入到文件
           fileOut = new FileOutputStream(file);
           if(fileOut!=null){
               int c = inputStream.read();
               while(c!=-1){
                   fileOut.write(c);
                   c = inputStream.read();
               }
           }
       } catch (Exception e) {
           e.printStackTrace();
       }finally{
           if(conn!=null){
               conn.disconnect();
           }


           /*
            * 必须关闭文件流
            * 否则JDK运行时,文件被占用其他进程无法访问
            */
           try {
               inputStream.close();
               fileOut.close();
           } catch (IOException e) {
               e.printStackTrace();
           }
       }
}













 
}
0 0
原创粉丝点击