http模拟post请求

public class HttpSender extends Thread{

    private static final String  COMPLEX_JSON_STR ="{\n" +
            "    \"order\": {\n" +
            "        \"items\": [\n" +
            "            {\n" +
            "                \"item\": \"AA-AAA-AAA\", \n" +
            "                \"qty\": 2, \n" +
            "                \"optional\": \"flash\"\n" +
            "            }, \n" +
            "            {\n" +
            "                \"item\": \"bb-bbb-bbb\", \n" +
            "                \"qty\": 3\n" +
            "            }\n" +
            "        ]\n" +
            "    }, \n" +
            "    \"preorder\": {\n" +
            "        \"items\": [\n" +
            "            {\n" +
            "                \"item\": \"cc-CCC-CCC\", \n" +
            "                \"qty\": 1\n" +
            "            }, \n" +
            "            {\n" +
            "                \"item\": \"dd-ddd-DDD\", \n" +
            "                \"qty\": 2\n" +
            "            }\n" +
            "        ]\n" +
            "    }, \n" +
            "    \"saveForLater\": {\n" +
            "        \"items\": [\n" +
            "            {\n" +
            "                \"item\": \"EE-EEE-eee\"\n" +
            "            }, \n" +
            "            {\n" +
            "                \"item\": \"FF-fff-fff\", \n" +
            "                \"qty\": 2\n" +
            "            }\n" +
            "        ]\n" +
            "    }, \n" +
            "    \"quote\": {\n" +
            "        \"items\": [\n" +
            "            {\n" +
            "                \"item\": \"GG-GGG-ggg\"\n" +
            "            }, \n" +
            "            {\n" +
            "                \"item\": \"HH-hhh-hhh\", \n" +
            "                \"qty\": 3\n" +
            "            }\n" +
            "        ]\n" +
            "    }\n" +
            "}";
    public static void main(String[] args) {
        HttpSender h1 = new HttpSender();
        HttpSender h2 = new HttpSender();
        HttpSender h3 = new HttpSender();
        HttpSender h4 = new HttpSender();
        h1.start();
        h2.start();
        h3.start();
        h4.start();
    }
    public void run(){
        while (true){

            String complexJsonStr = COMPLEX_JSON_STR;
            String s = JSON.toJSONString(complexJsonStr);
            String getResult=HttpSender.doHttpPost(complexJsonStr,"http://10.16.238.104:8080/api/v1/shoppingcart?deviceid=188339516.999.80529.3376331175.1476780001.1476780001.1&countrycode=USA&customerNumber=02983902559");
            //String getResult=HttpSender.sendGet("http://10.16.238.104:8082/api/v1/shoppingcart?deviceid=188339516.999.80529.3376331175.1476780001.1476780001.1&countrycode=USA&customerNumber=02983902559");
            System.out.println(getResult);
        }
    }
  /*  public static String sendGet(String url) {
        //1.获得一个httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        //2.生成一个get请求
        HttpGet httpget = new HttpGet(url);
        CloseableHttpResponse response = null;
        try {
            //3.执行get请求并返回结果
            response = httpclient.execute(httpget);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        String result = null;
        try {
            //4.处理结果,这里将结果返回为字符串
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }*/
  public static String sendPost(String url, Map<String, String> map) {
      List<NameValuePair> formparams = new ArrayList<NameValuePair>();
      for (Map.Entry<String, String> entry : map.entrySet()) {
          formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
      }
      UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
      HttpPost httppost = new HttpPost(url);
      httppost.setEntity(entity);
      CloseableHttpResponse response = null;
      try {
//          response = httpclient.execute(httppost);
      } catch (Exception e) {
          e.printStackTrace();
      }
      HttpEntity entity1 = response.getEntity();
      String result = null;
      try {
          result = EntityUtils.toString(entity1);
      } catch (Exception e) {
          e.printStackTrace();
      }
      return result;
  }


    public static String doHttpPost(String xmlInfo, String URL) {
        System.out.println("发起的数据:" + xmlInfo);
        byte[] xmlData = xmlInfo.getBytes();
        InputStream instr = null;
        java.io.ByteArrayOutputStream out = null;
        try {
            URL url = new URL(URL);
            URLConnection urlCon = url.openConnection();
            urlCon.setDoOutput(true);
            urlCon.setDoInput(true);
            urlCon.setUseCaches(false);
            urlCon.setRequestProperty("content-Type", "application/json");
            urlCon.setRequestProperty("charset", "utf-8");
            urlCon.setRequestProperty("Content-length",
                    String.valueOf(xmlData.length));
            System.out.println(String.valueOf(xmlData.length));
            DataOutputStream printout = new DataOutputStream(
                    urlCon.getOutputStream());
            printout.write(xmlData);
            printout.flush();
            printout.close();
            instr = urlCon.getInputStream();
            byte[] bis = IOUtils.toByteArray(instr);
            String ResponseString = new String(bis, "UTF-8");
            if ((ResponseString == null) || ("".equals(ResponseString.trim()))) {
                System.out.println("返回空");
            }
            System.out.println("返回数据为:" + ResponseString);
            return ResponseString;

        } catch (Exception e) {
            e.printStackTrace();
            return "0";
        } finally {
            try {
                out.close();
                instr.close();

            } catch (Exception ex) {
                return "0";
            }
        }
    }


    /*public static String sendPost(String url) {
        //1.获得一个httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        //2.生成一个post请求
        HttpPost httppost = new HttpPost(url);
        CloseableHttpResponse response = null;
        try {
            //3.执行post请求并返回结果
            response = httpclient.execute(httppost);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //4.处理结果,这里将结果返回为字符串
        HttpEntity entity = response.getEntity();
        String result = null;
        try {
            result = EntityUtils.toString(entity);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }*/
    /*public static String sendPost(String url) {
        OutputStreamWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            HttpURLConnection conn = null;

                conn = (HttpURLConnection) realUrl.openConnection();

            // 打开和URL之间的连接

            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");    // POST方法


            // 设置通用的请求属性

            conn.setRequestProperty("accept", "");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            conn.connect();

            // 获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            // 发送请求参数
            out.write(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;
    }*/





}

猜你喜欢

转载自blog.csdn.net/yu849893679/article/details/84892061