- UID
- 1054
- 精华
- 积分
- 55
- 威望
- 点
- 宅币
- 个
- 贡献
- 次
- 宅之契约
- 份
- 最后登录
- 1970-1-1
- 在线时间
- 小时
|
楼主 |
发表于 2015-12-28 22:02:14
|
显示全部楼层
这是控制台程序,调用有道api,post提交
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
public class TestPost {
public static void main(String[] args) {
new ReadByPost().start();
}
}
class ReadByPost extends Thread {
@Override
public void run() {
try {
URL url = new URL("http://fanyi.youdao.com/openapi.do");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.addRequestProperty("encoding", "UTF-8");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
OutputStream os = connection.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
Scanner in = new Scanner(System.in);
String text = "keyfrom=fadabvaa&key=522071532&type=data&doctype=json&version=1.1&q=" + in.nextLine();
bw.write(text);
bw.flush();
InputStream is = connection.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "UTF-8");
BufferedReader br = new BufferedReader(isr);
String line;
StringBuilder builder = new StringBuilder();
while ((line = br.readLine()) != null) {
String[] arr = line.split("]");
for (int i = 0; i < arr.length; i++) {
if (arr[i].contains("translation")) {
System.out.println(arr[i].substring(17, arr[i].length()-1));
}
}
}
bw.close();
osw.close();
os.close();
br.close();
isr.close();
is.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
|