最简单的图灵机器人接口测试之返回消息

eclipse上新建一个Java类,写一个http请求,传入图灵接口需要的参数,然后正确返回结果,

代码如下:

package com.han.test;

import java.io.BufferedReader;

import java.io.DataOutputStream;

import java.io.IOException;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;

import java.net.URLEncoder;

public class T1 {

public static void main(String[] args) throws IOException {

readContentFromPost();

}

public static void readContentFromPost() throws IOException {

// Post请求的url,与get不同的是不需要带参数

URL postUrl = new URL("http://www.tuling123.com/openapi/api");

// 打开连接

HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();

// 设置是否向connection输出,因为这个是post请求,参数要放在

// http正文内,因此需要设为true

connection.setDoOutput(true);

// Read from the connection. Default is true.

connection.setDoInput(true);

// 默认是 GET方式

connection.setRequestMethod("POST");

// Post 请求不能使用缓存

connection.setUseCaches(false);

connection.setInstanceFollowRedirects(true);

// 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的

// 意思是正文是urlencoded编码过的form参数,下面我们可以看到我们对正文内容使用URLEncoder.encode

// 进行编码

connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

// 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,

// 要注意的是connection.getOutputStream会隐含的进行connect。

connection.connect();

DataOutputStream out = new DataOutputStream(connection.getOutputStream());

// The URL-encoded contend

// 正文,正文内容其实跟get的URL中 '? '后的参数字符串一致

String content = "key=" + URLEncoder.encode("这个地方写入自己图灵接口中的key", "UTF-8");

content += "&info=" + URLEncoder.encode("快递查询199216505651", "UTF-8");

;

// DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写到流里面

out.writeBytes(content);

out.flush();

out.close();

BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

String line;

while ((line = reader.readLine()) != null) {

System.out.println(line);

}

reader.close();

connection.disconnect();

}

}

返回结果如图

我的博客地址:http://hanyz.cn

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,067评论 19 139
  • /Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home...
    光剑书架上的书阅读 3,977评论 2 8
  • 前言:近期在慕课网学习了慕课网课程Android中的HTTP通信,就自己总结了一下,其中参考了不少博文,感谢大家的...
    mecury阅读 2,346评论 1 10
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,785评论 18 399
  • 文/晴天过后上一章 目录 A城青竹湖月亮湾,黎志轩正坐在自家别墅的凉亭里发呆,回来已经有近两个月了,...
    晴天过后阅读 709评论 7 22