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

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 params,      String encode,String PATH) {    StringBuffer stringBuffer = new StringBuffer();    if (params != null && !params.isEmpty()) {      for (Map.Entry 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 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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值