zoukankan      html  css  js  c++  java
  • http post/get 2种使用方式

    
    
    public class HttpUtil {
    
    
    
     //HttpPost
     public static String executePost(String url, List<NameValuePair> list) {
      HttpPost post = new HttpPost(url);
      // HttpDelete
      // post.addHeader("Authorization", "MDowMDExMTExMTExMTE="); // 认证token
      // post.addHeader("Content-type", "text/xml;charset=UTF-8");
      // post.addHeader("Connection", "keep-alive");
      if (list != null && list.size() > 0) {
       try {
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,
          HTTP.UTF_8);
        post.setEntity(entity);
       } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
       }
      }
      HttpClient client = new DefaultHttpClient();
      try {
       HttpResponse response = client.execute(post);
    
    //   response.getHeaders("Authorization");   ????????????????????token?
    
       if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        String result = EntityUtils.toString(response.getEntity());
        return result;
       } else {
        return "-2";
       }
      } catch (Exception e) {
       e.printStackTrace();
      }
      return "-2";
     }
    
     //HttpGet
     public static String executeGet(String url, Map<String, String> params, String encoding) throws Exception {
    
      // 使用StringBuilder对象
      StringBuilder sb = new StringBuilder(url);
      sb.append('?');
    
      // 迭代Map
      for (Map.Entry<String, String> entry : params.entrySet()) {
       sb.append(entry.getKey()).append('=').append(
         URLEncoder.encode(entry.getValue(), encoding)).append('&');
      }
      sb.deleteCharAt(sb.length() - 1);
      // 打开链接
      URL url2 = new URL(sb.toString());
      HttpGet get = new HttpGet(url2);
      // HttpDelete
      // get .addHeader("Authorization", "MDowMDExMTExMTExMTE="); // 认证token
      // get .addHeader("Content-type", "text/xml;charset=UTF-8");
      // get .addHeader("Connection", "keep-alive");
    
      // HttpParams params = new BasicHttpParams();
      // ConnManagerParams.setTimeout(params, 20000);
      // get.setParams(params);
      HttpClient client = new DefaultHttpClient();
      try {
       HttpResponse response = client.execute(get);
       if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        String result = EntityUtils.toString(response.getEntity());
        return result;
       } else {
        return "-2";
       }
      } catch (Exception e) {
       e.printStackTrace();
      }
      return "-2";
     }
    
    
    
    HttpURLConnection 方式:
    =====================
    
    
     //HttpURLConnection  get
    
      public void sendSms() throws Exception{
            String message="货已发到";
            message=URLEncoder.encode(message, "UTF-8");
            System.out.println(message);
            String path ="http://localhost:8083/DS_Trade/mobile/sim!add.do?message="+message;
            URL url =new URL(path);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setConnectTimeout(5*1000);
            conn.setRequestMethod("GET");
            InputStream inStream = conn.getInputStream();    
            byte[] data = StreamTool.readInputStream(inStream);
            String result=new String(data, "UTF-8");
            System.out.println(result);
        }
    
    
     HttpURLConnection方式:
    
     //HttpURLConnection  post
    
     public static String uploads(String xml, String path, String authorization) {
      try {
       byte[] data = xml.getBytes("UTF-8");
       URL url = new URL(path);
       HttpURLConnection conn = (HttpURLConnection) url.openConnection();
       conn.setConnectTimeout(8 * 1000);
       conn.setReadTimeout(8 * 1000);
       conn.setDoInput(true);// 允许输入
       conn.setDoOutput(true);// 允许输出
       conn.setUseCaches(false);
       conn.setRequestMethod("POST"); // Post方式
       conn.setRequestProperty("connection", "keep-alive"); // 客户端到服务器端的连接持续有效
       conn.setRequestProperty("Authorization", authorization);
       conn.setRequestProperty("Content-Type",
         "application/json; charset=UTF-8");
       conn.setRequestProperty("Content-Length",
         String.valueOf(data.length));
    
       OutputStream outStream = conn.getOutputStream();
       outStream.write(data);
       outStream.flush();
       outStream.close();
       StringBuffer buf = new StringBuffer();
       String s = "";
    
       if (conn.getResponseCode() == 200) {
        InputStream in = conn.getInputStream();
        BufferedReader br = new BufferedReader(
          new InputStreamReader(in));
        while ((s = br.readLine()) != null) {
         buf.append(s);
        }
        br.close();
        in.close();
       }
       return buf.toString();
      } catch (Exception e) {
       e.printStackTrace();
      }
      return "-2";
     }
    
    }
    
  • 相关阅读:
    C# Trick
    DotNet Resource
    人员角色权限
    Verticles for Web Application
    Node Addon
    EventBus
    怎么实现员工和工资大数据分析,echarts+js实现
    winform怎么实现财务上凭证录入和打印
    WPF实现大数据分析
    非常经典的面试题,方案很多,一起交流学习
  • 原文地址:https://www.cnblogs.com/melons/p/5791918.html
Copyright © 2011-2022 走看看