Java以Post方式访问spring的action

对方定义的Web接口,接收JSON对象,返回也是JSON对象。

在编码过程中遇到了一点小问题,以下是完整代码。

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import net.sf.json.JSONObject;

public class HttpPost {

	private JSONObject Send(String urlStr, JSONObject jObj) throws IOException {
		String retValue = null;

		URL url = new URL(urlStr);
		HttpURLConnection con = (HttpURLConnection) url.openConnection();
		// 以Post方式发送
		con.setRequestMethod("POST");
		con.setDoInput(true);
		con.setDoOutput(true);
		// 设置内容类型为文本或者html
		con.setRequestProperty("Content-type", "text/html");

		PrintWriter out = new PrintWriter(con.getOutputStream());
		// 对方接口要求带[]符号
		out.println("[" + jObj.toString() + "]");
		out.flush();
		out.close();

		BufferedReader l_reader = new BufferedReader(new InputStreamReader(
				con.getInputStream()));
		StringBuffer buff = new StringBuffer();
		String line;
		while ((line = l_reader.readLine()) != null) {
			buff.append(line + "\n");
		}
		l_reader.close();
		con.disconnect();

		retValue = buff.toString();
		if (retValue.length() > 2) {
			retValue = retValue.substring(1, retValue.length() - 2);
			return JSONObject.fromObject(retValue);
		} else
			return null;
	}

	public static void main(String[] args) throws IOException {
		HttpPost hp = new HttpPost();
		JSONObject jUser = new JSONObject();
		jUser.put("userName", "njupt");
		JSONObject jUserAcs = new JSONObject();
		jUserAcs.put("UserAccess", jUser);

		System.out
				.println(hp
						.Send("http://ip:port/smartHome/mobile/UserAccess.action",
								jUserAcs));
	}
}

 

JSON用到的jar包可以从这里下载:http://134.iteye.com/blog/231782

推荐一个http抓包工具HTTP Analyzer:http://www.ieinspector.com/httpanalyzer/download.html

用它来分析发送和接收的内容,之前一直调试不通过,因为request的contenttype不是text/html,是使用该抓包工具发现的。

 

以上

 

wuxiaochao@live.com

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值