java使用URLConnection类发送http POST请求,javaurlconnection,下面的例子展示使用URL
分享于 点击 9157 次 点评:11
java使用URLConnection类发送http POST请求,javaurlconnection,下面的例子展示使用URL
下面的例子展示使用URLConnection类发送post请求,发送两个参数width和height。
我们使用URL和URLConnection类来打开目标连接,然后通过URLConnection类的getOutputStream()方法获得输出流,然后将要POST的参数写入到输出流中。
使用URLConnection的getInputStream()方法得到输入流,从输入流中可以得到http响应的内容
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.net.MalformedURLException;import java.net.URL;import java.net.URLConnection;/** * Main.java * * @author byrx.net */public class Main { /** * 发送Post请求 */ public void sendPostRequest() { //Build parameter string String data = "width=50&height=100"; try { // Send the request URL url = new URL("http://www.somesite.com"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); //write parameters writer.write(data); writer.flush(); // Get the response StringBuffer answer = new StringBuffer(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = reader.readLine()) != null) { answer.append(line); } writer.close(); reader.close(); //Output the response System.out.println(answer.toString()); } catch (MalformedURLException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } /** * Starts the program * * @param args the command line arguments */ public static void main(String[] args) { new Main().sendPostRequest(); }}
用户点评