java发送get、post http请求

3 篇文章 0 订阅

直接上代码

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import javax.servlet.http.HttpServletRequest;

import org.jdom.CDATA;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.output.XMLOutputter;

public class OperationDao {

	public static String sendRequest(OperationBeanBase opBean)
			throws JDOMException, Exception {
		if (opBean.getRequestType().equals("post"))
			return sendPostRequest(opBean);
		else if (opBean.getRequestType().equals("get"))
			return sendGetRequest(opBean);
		return "";
	}

	public static String sendPostRequest(OperationBeanBase opBean)
			throws JDOMException, Exception {
		URL url = new URL(opBean.getUrlString());
		URLConnection con = url.openConnection();
		con.setUseCaches(false);
		con.setDoOutput(true);//开启输入输出
  		con.setDoInput(true);

		BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
				con.getOutputStream(),"UTF-8"));
		out.write(opBean.getXMLString());
		out.flush();
		out.close();

		StringBuffer sendBack = new StringBuffer();
		try {
			InputStream is = con.getInputStream();
			InputStreamReader isr = new InputStreamReader(is,"UTF-8");
			BufferedReader br = new BufferedReader(isr);
			String s = "";
			while ((s = br.readLine()) != null) {
				sendBack.append(s);
			}
		} catch (Exception e) {
			System.out.println(e.toString());
		}

		return sendBack.toString();
	}

	public static String sendGetRequest(OperationBeanBase opBean)
			throws JDOMException, Exception {
		URL url = new URL(opBean.getUrlString());
		URLConnection con = url.openConnection();
		con.connect();
		StringBuffer sendBack = new StringBuffer();		
		try {
			InputStream is = con.getInputStream();
			InputStreamReader isr = new InputStreamReader(is,"UTF-8");
			BufferedReader br = new BufferedReader(isr);
			String s = "";
			while ((s = br.readLine()) != null) {
				sendBack.append(s);
			}
		} catch (Exception e) {
			System.out.println(e.toString());
		}
		
		// System.out.println(sendBack);
		return sendBack.toString();
	}

}

网上还有一个版本是模拟ajax的异步请求。有异步需求的朋友可以参考那篇文章。


今天又找打基于HttpURLConnection的实现

参考地址:http://code.google.com/intl/zh-TW/appengine/docs/java/urlfetch/usingjavanet.html

import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStreamWriter;

// ...
        String message = URLEncoder.encode("my message", "UTF-8");

        try {
            URL url = new URL("http://www.example.com/comment");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");

            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
            writer.write("message=" + message);
            writer.close();
    
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                // OK
            } else {
                // Server returned HTTP error code.
            }
        } catch (MalformedURLException e) {
            // ...
        } catch (IOException e) {
            // ...
        }

好处是可以得到http状态,进行判断。

若要在外寄要求中設定 HTTP 标头,调用 HttpURLConnection 的 setRequestProperty() 方法

 connection.setRequestProperty("X-MyApp-Version", "2.7.3");

根据预设,HttpURLConnection 將随着 HTTP 重新导向。URL 拾取服务最多将进行 5 次重新导向。
若要停用下列重新导向,调用 HttpURLConnection 的 setFollowRedirects() 方法:

connection.setFollowRedirects(false);


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值