使用 Http 的 Post 方式与网络交互通信
package zw1;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.sound.sampled.AudioFormat.Encoding;
import org.omg.CORBA.portable.OutputStream;
public class post1 {
public static void main(String[] args) {
new ReadByPost().start();
}
static class ReadByPost extends Thread{
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 outputStream = connection.getOutputStream();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
bufferedWriter.write("?keyfrom=<keyfrom>&key=<key>&type=data&doctype=xml&version=1.1&q=result");//写入参数
bufferedWriter.flush();//强制执行
//对输入流包装
InputStream inputStream = connection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader =new BufferedReader(inputStreamReader);
String line;
StringBuilder builder = new StringBuilder();
while ((line=bufferedReader.readLine()) != null) {
builder.append(line);
}
bufferedWriter.close();
outputStreamWriter.close();
outputStream.close();
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
System.out.println(builder.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
}