java,python,scala发送http请求

项目github地址:bitcarmanlee easy-algorithm-interview-and-practice
欢迎大家star,留言,一起学习进步

项目中经常有发送http请求的需求,现在将java,python,scala中发送http请求的方法稍作记录,以备不时之需。

1.java版本

java代码相对来说最为冗长。。。这也是java的一贯风格。。。

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;


public class HttpUtils {

    protected static Logger LOGGER = LoggerFactory.getLogger(HttpUtils.class);

    public static HttpClient httpClient = new DefaultHttpClient();

    public static String getResponse(String url, int retryTimes) {
        for(int i = 0; i < retryTimes; i++) {
            LOGGER.info("get response with the request: {}", url);
            try {
                HttpResponse response = httpClient.execute(new HttpGet(url));
                HttpEntity entity = response.getEntity();
                if(response.getStatusLine().getStatusCode() == 200) {
                    String res = genResponseContext(entity.getContent());
                    if(StringUtils.isNotBlank(res)) return res;
                }

            } catch (Exception ex) {
                System.out.println("get response with error");
                ex.printStackTrace();
                LOGGER.error("get response with error: \n", ex);
                try {
                    Thread.sleep(1000 * (i + 1));
                } catch (InterruptedException interEx) {
                    interEx.printStackTrace();
                }
            }
        }

        return StringUtils.EMPTY;
    }

    public static String genResponseContext(InputStream is) {
        BufferedReader reader = null;
        try {
            StringBuilder sb = new StringBuilder();
            reader = new BufferedReader(new InputStreamReader(is));
            String line;
            while( (line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
            return sb.toString().trim();
        } catch (Exception ex) {
            LOGGER.error("get response error: {} \n", ex);
            return null;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (Exception e) {
                }
            }
        }
    }

    public static void main(String[] args) {
        String url = "http://www.baidu.com";
        String result = getResponse(url, 2);
        System.out.println(result);
    }
}

2.python版本

python代码相对来说就简单很多了。。。

#!/usr/bin/env python
# -*- coding: utf-8

import urllib2


def send_http_request(url):
    request = urllib2.Request(url)
    response = urllib2.urlopen(request)
    data = response.read()
    print data


send_http_request("http://www.baidu.com")

3.scala版本

scala也是JVM系,所以跟java版本有一点像,但简洁很多。

import org.apache.http.client.methods.HttpGet
import org.apache.http.impl.client.DefaultHttpClient

import scala.io.Source

object HttpUtils {

    def send_http_request(url: String): Unit = {
        val httpclient = new DefaultHttpClient()
        try {
            val response = httpclient.execute(new HttpGet(url))
            val entity = response.getEntity
            val result = Source.fromInputStream(entity.getContent).getLines().mkString("\n")
            println(result)
        } catch {
            case ex: Exception => ex.printStackTrace()
        }
    }

    def main(args: Array[String]): Unit = {
        val url = "http://www.baidu.com"
        send_http_request(url)
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是Java程序接入Chat GPT的步骤和代码实现: 1.前置准备: 在使用Chat GPT 2之前,需要先注册并获取API Key。注册地址为:https://www.chatie.io/register.html 2.官方支持接入语言: 目前Chat GPT 2官方支持的接入语言有:PythonJava、PHP、Node.js、Go、C#、Ruby、Shell、Perl、Swift、Objective-C、C++、Dart、Kotlin、Scala、Rust、Lua、Erlang、Haskell、Groovy、Clojure、OCaml、F#、Elixir、Julia、R、PowerShell、Scheme、Fortran、Ada、Prolog、Lisp、Bash、Tcl、Assembly、Smalltalk、Pascal、Visual Basic、COBOL、Logo、Forth、Rexx、Awk、sed、Yacc、Lex、M4、Makefile、Batch、ActionScript、ColdFusion、Delphi、Eiffel、Forth、FoxPro、IDL、LabVIEW、Matlab、Objective-C++、Perl6、PL/I、PostScript、RPG、SAS、SPSS、SQL、Verilog、VHDL、XSLT等。 3.调用费用: Chat GPT 2提供免费试用,每个月可以免费调用1000次API,超过1000次需要付费。 4.接口调用说明: Chat GPT 2的API接口地址为:https://api.chatie.io/chatgpt2/ask 请求方式为POST,请求参数为text和apikey,其中text为输入的文本,apikey为注册时获取的API Key。 5.代码实现: 以下是Java程序调用Chat GPT 2的示例代码: ```java import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; public class ChatGPT2Demo { public static void main(String[] args) { String question = "你好"; String apiKey = "your_api_key"; try { String urlStr = "https://api.chatie.io/chatgpt2/ask?text=" + URLEncoder.encode(question, "UTF-8") + "&apikey=" + apiKey; URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setDoOutput(true); BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output; while ((output = br.readLine()) != null) { System.out.println(output); } conn.disconnect(); } catch (Exception e) { e.printStackTrace(); } } } ``` 6.小结: 以上就是Java程序接入Chat GPT 2的全部步骤和代码实现,通过以上步骤可以轻松地在Java程序中接入Chat GPT 2,实现智能问答功能。 --相关***. Chat GPT 2的免费试用次数是多少?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值