okhttp访问问题

记录一下今天开发过程中的问题

问题起因:

公司通过dify进行大模型的交互,我是后端,负责后台请求的接入,后面发现了官方的java-client,就下载下来测试,官方案例如下:

import ai.dify.javaclient.DifyClient; import ai.dify.javaclient.ChatClient; import ai.dify.javaclient.CompletionClient; import okhttp3.Response;

 public class DifyApp {
 private static final String API_KEY = "your-api-key-here";
 
 public static void main(String[] args) {
    try {
        String user = "random-user-id";
        String inputs = "{\"name\":\"test name a\"}";
        String query = "Please tell me a short story in 10 words or less.";
        boolean responseMode = true;
 
        // Create a completion client
        CompletionClient completionClient = new CompletionClient(API_KEY);
        Response completionResponse = completionClient.createCompletionMessage(inputs, query, user, responseMode);
        System.out.println(completionResponse.body().string());
 
        // Create a chat client
        ChatClient chatClient = new ChatClient(API_KEY);
        // Create a chat message
        Response chatResponse = chatClient.createChatMessage(inputs, query, user, true, null);
        System.out.println(chatResponse.body().string());
 
        // Fetch conversations
        chatClient.getConversations(user);
        // Rename conversation
        String conversationId = "example-conversation-id";
        String name = "new-name";
        chatClient.renameConversation(conversationId, name, user);
 
        // And so on for other methods...
 
        DifyClient client = new DifyClient(API_KEY);
        // Fetch application parameters
        client.getApplicationParameters(user);
 
        // Provide feedback for a message
        String messageId = "your-message-id";
        String rating = "5";
        client.messageFeedback(messageId, rating, user);
 
    } catch (Exception e) {
        e.printStackTrace();
    }
 }}

发现返回的请求失败

于是采用curl测试,代码如下

 curl -X POST 'http://localhost:9000/v1/completion-messages' \
 --header 'Authorization: Bearer app-EDKz7as0jjVKj21lUhnEUSrB' \
 --header 'Content-Type: application/json' \
 --data-raw '{
    "inputs": {"query": "Hello, world!"},
    "response_mode": "streaming",
    "user": "abc-123",
 
 "query": "Hello, world!"
 
 }'

请求成功,接着使用postman测试,也成功了,于是进行了长达两个小时的测试,没有发现任何不对的地方

我想着官方使用okhttp写的,我用java原生API自己写一个试试,成功了,原生写法如下:

 public void test1() {
 try {
     // 定义Dify后台的URL
     String urlString = "http://localhost:9000/v1/completion-messages"; // 替换为实际的Dify后台URL
 
     // 创建URL对象
     URL url = new URL(urlString);
 
     // 打开连接
     HttpURLConnection connection = (HttpURLConnection) url.openConnection();
 
     // 设置请求方法为POST
     connection.setRequestMethod("POST");
 
     // 添加请求头
     connection.setRequestProperty("Authorization", "Bearer app-RmUVDswZjVUyaDeAYkfcX9xu");
     connection.setRequestProperty("Content-Type", "application/json");
 
     // 允许向服务器写入数据
     connection.setDoOutput(true);
 
     // 构建请求体数据
     String requestBody = "{\"inputs\":{\"query\":\"Hello, world!\"},\"response_mode\":\"streaming\",\"user\":\"abc-123\",\"query\":\"1111\"}";
 
     // 发送请求体数据
     DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
     outputStream.writeBytes(requestBody);
     outputStream.flush();
     outputStream.close();
 
     // 获取响应代码
     int responseCode = connection.getResponseCode();
     System.out.println("Response Code: " + responseCode);
 
     // 读取响应内容
     BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
     String line;
     StringBuilder response = new StringBuilder();
     while ((line = reader.readLine()) != null) {
         response.append(line);
    }
     reader.close();
 
     // 输出响应内容
     System.out.println("Response: " + response.toString());
 
     // 关闭连接
     connection.disconnect();
 } catch (Exception e) {
     e.printStackTrace();
 }}

于是,我又使用apache httpclient又写了一套,结果还是成功了

代码如下:

 public void test2() {
     try {
         // 定义Dify后台的URL
         String urlString = "http://localhost:9000/v1/completion-messages"; // 替换为实际的Dify后台URL
 
         // 创建HttpClient实例
         HttpClient httpClient = HttpClientBuilder.create().build();
 
         // 创建HttpPost请求
         HttpPost httpPost = new HttpPost(urlString);
 
         // 添加请求头
         httpPost.setHeader("Authorization", "Bearer app-RmUVDswZjVUyaDeAYkfcX9xu");
         httpPost.setHeader("Content-Type", "application/json");
 
         // 构建请求体数据
         String requestBody = "{\"inputs\":{\"query\":\"Hello, world!\"},\"response_mode\":\"streaming\",\"user\":\"abc-123\",\"query\":\"1111\"}";
 
         // 设置请求体
         StringEntity entity = new StringEntity(requestBody);
         httpPost.setEntity(entity);
 
         // 发送POST请求
         HttpResponse response = httpClient.execute(httpPost);
 
         // 获取响应代码
         int statusCode = response.getStatusLine().getStatusCode();
         System.out.println("Response Code: " + statusCode);
 
         // 读取响应内容
         HttpEntity responseEntity = response.getEntity();
         String responseBody = EntityUtils.toString(responseEntity);
         System.out.println("Response: " + responseBody);
 
         // 关闭连接
 
    } catch (Exception e) {
         e.printStackTrace();
    }
 }
 
posted @ 2024-05-15 15:57  ArGilgamesh  阅读(210)  评论(0)    收藏  举报