http post發送請求

一:

用java自帶URL發送
public synchronized JSONObject getJSON(String url2, String param) {
           try {
                URL url = new URL(url2);
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                con.setDoOutput(true); //獲取返回數據須要設置爲true 默認false
                con.setDoInput(true); //發送數據須要設置爲true 默認false
                con.setReadTimeout(5000);
                con.setConnectTimeout(5000);
                con.setRequestMethod("POST");
                con.connect();
                DataOutputStream out = new DataOutputStream(con.getOutputStream());
                if (param != null) {
                     param = URLEncoder.encode(param,"utf-8");//url編碼防止中文亂碼
                     out.writeBytes(param);
                }
                out.flush();
                out.close();
                BufferedReader red = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));
                StringBuffer sb = new StringBuffer();
                String line;
                while ((line = red.readLine()) != null) {
                     sb.append(line);
                }
                red.close();
                return JSONObject.fromObject(sb);
           } catch (Exception e) {
                e.printStackTrace();
                return null;
           }
     }

二:apache httppost方式

 
/**
      * post請求,發送json數據
      *
      * @param url
      * @param json
      * @return
      */
     public static JSONObject doPost(String url, String json) {
           HttpPost post = new HttpPost(url);
           JSONObject response = null;
           try {
                StringEntity s = new StringEntity(json, "UTF-8"); // 中文亂碼在此解決
                s.setContentType("application/json");
                post.setEntity(s);
                HttpResponse res = HttpClients.createDefault().execute(post);
                if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                     String result = EntityUtils.toString(res.getEntity());// 返回json格式:
                     response = JSON.parseObject(result);
                }
           } catch (Exception e) {
                e.printStackTrace();
           }
           return response;
     }

三: httppost 發送map
 
   /**
      * post請求
      *
      * @param url
      * @param param
      * @return
      */
     public static String httpPost(String url, Map<String, Object> map) {
           try {
                HttpPost post = new HttpPost(url);
        //requestConfig post請求配置類,設置超時時間
                RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setSocketTimeout(50000).build();
                post.setConfig(requestConfig);
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                     if (entry.getValue() != null && entry.getValue() != "") {
              //用basicNameValuePair來封裝數據
                           params.add(new BasicNameValuePair(entry.getKey(), entry.getValue() + ""));
                     }
                }
          //在這個地方設置編碼 防止請求亂碼
                post.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
                GeneralLog.info(ModelName, "請求url:" + url);
                GeneralLog.info(ModelName, "請求數據:" + map);
                CloseableHttpResponse httpResponse = HttpClients.createDefault().execute(post);
                System.out.println("返回數據:" + httpResponse);
                String result = null;
                if (httpResponse.getStatusLine().getStatusCode() == 200) {
                     HttpEntity httpEntity = httpResponse.getEntity();
                     result = EntityUtils.toString(httpEntity);// 取出應答字符串
                }
                return result;
           } catch (Exception e) {
                e.printStackTrace();
                return null;
           }
     }
相關文章
相關標籤/搜索