各语言发起http请求的方法

golang

get

func (r *Rescanner) doGet(url string) ([]byte, error) {
      request, err := http.NewRequest("GET", url, nil)
      if err != nil {
          return nil, err 
      }   
      res, err := http.DefaultClient.Do(request)
      if err != nil {
          return nil, err 
      }   
      if res.StatusCode != 200 {
          return nil, fmt.Errorf("http response code is error,err:" + err.Error())
      }   
      body, err := ioutil.ReadAll(res.Body)
      if err != nil {
          return nil, err 
      }   
      return body, nil 
  }

post

// paramas 是kv类型
func (j *Judger) doPost(xml string, params map[string]string) (string, error) {
      client := &http.Client{
          Timeout: 3 * time.Second,
      }   
      body := &bytes.Buffer{}
      writer := multipart.NewWriter(body)
  
      for key, val := range params {
          _ = writer.WriteField(key, val)
      }   
      err := writer.Close()
      if err != nil {
          log.Warnf("write post parameters error")
          return "", nil 
      }   
  
      request, err := http.NewRequest("POST", Url, body)
      request.Header.Set("Content-Type", writer.FormDataContentType())
      resp, err := client.Do(request)
      if err != nil {
          log.Warnf("request error")
          return "", err 
      } else {
          body := &bytes.Buffer{}
          _, err := body.ReadFrom(resp.Body)
          defer resp.Body.Close()
          if err != nil {
              log.Warnf("read response body error")
              return "", err 
          }   
          return body.String(), nil 
      }   
  }

python

get

import requests

start_url = 'https://www.baidu.com'
response = requests.get(url=start_url)
print(response)    # 返回值:

post

def post(client, total):
        headers = {'content-type': 'application/json'}
        req = {
                "date" : yesterday,
                "client" : client,
                "Count" : total
                }
        print json.dumps(req)
        res = requests.post(url, data = json.dumps(req), headers = headers)
        print res.text
        print res.status_code

Java

get

public String doGet(String url) throws Exception {

        InputStream is = null;
        BufferedReader br = null;
        String result = null;

        URL url = new URL(url);

        HttpURLConnection connection = null;
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(15000);
        connection.setReadTimeout(60000);
        connection.connect();
        if (connection.getResponseCode() == 200) {
            is = connection.getInputStream();
            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            // 存放数据
            StringBuffer sbf = new StringBuffer();
            String temp = null;
            while ((temp = br.readLine()) != null) {
                sbf.append(temp);
                sbf.append("\n");
            }
            result = sbf.toString();
            br.close();
            is.close();
            connection.disconnect();
            return result;
        }
        return "";
    }

post

public String doPost(String url, HashMap params) {

        BufferedReader in = null;
        try {

            HttpClient client = HttpClientBuilder.create().build();
            HttpPost request = new HttpPost();
            request.setURI(new URI(url));

            List nvps = new ArrayList();
            for (Iterator iter = params.keySet().iterator(); iter.hasNext(); ) {
                String name = (String) iter.next();
                String value = String.valueOf(params.get(name));
                nvps.add(new BasicNameValuePair(name, value));
            }
            request.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

            HttpResponse response = client.execute(request);
            int code = response.getStatusLine().getStatusCode();
            if (code == 200) {
                in = new BufferedReader(new InputStreamReader(response.getEntity()
                        .getContent(), "utf-8"));
                StringBuffer sb = new StringBuffer("");
                String line = "";
                String NL = System.getProperty("line.separator");
                while ((line = in.readLine()) != null) {
                    sb.append(line + NL);
                }
                in.close();

                return sb.toString();
            } else {
                this.logger.error("request error, status code:" + code);
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

你可能感兴趣的:(http)