JAVA两种POST请求方式

package com.ssh.insure.utils;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;

public class POSTUtil {
	
	/**
	 * 传统的POST/GET 请求方式
	 * @param toURL
	 * @param data
	 * @return
	 * @throws Exception
	 */
	public static String requestServiceJson(String toURL, String data)
			throws Exception {
		StringBuffer bs = new StringBuffer();
		URL sendUrl = new URL(toURL.trim());
		URLConnection connection = sendUrl.openConnection();
		connection.setConnectTimeout(30000);
		connection.setReadTimeout(30000);
		connection.setDoOutput(true);
		connection.setRequestProperty("Content-Type","application/json;chert=UTF-8");
		OutputStreamWriter out = new OutputStreamWriter(
				connection.getOutputStream(), "UTF-8");
		out.write(data);
		out.flush();
		out.close();
		connection.connect();
		InputStream is = connection.getInputStream();
		BufferedReader buffer = new BufferedReader(new InputStreamReader(is,"UTF-8"));

		String l = null;
		while ((l = buffer.readLine()) != null) {
			bs.append(l);
		}
		return bs.toString();
	}
	

	/**
	 * 遇到了java.io.IOException: Server returned HTTP response code: 500 for URL错误信息,网上找了很多,例如修改User-Agent等都没能解决,我感觉还是java 客户端的访问被拒绝了,
	 * 最后使用了org.apache.commons.httpclient.HttpClient包,通信代码如下:
	 * @param toURL url
	 * @param data 报文
	 * @return 响应信息
	 * @throws Exception
	 */
	public static String TCRequestJsonS(String toURL, String data) throws Exception {
		byte[] requestBytes;
		String soapRequestInfo = data;
		requestBytes = soapRequestInfo.getBytes("utf-8");
		HttpClient httpClient = new HttpClient();
		PostMethod postMethod = new PostMethod(toURL);
		postMethod.setRequestHeader("SOAPAction", "http://tempuri.org/GetMiscInfo");//Soap Action Header!
		InputStream inputStream = new ByteArrayInputStream(requestBytes, 0, requestBytes.length);
		RequestEntity requestEntity = new InputStreamRequestEntity(inputStream, requestBytes.length, "application/json; charset=utf-8");
		postMethod.setRequestEntity(requestEntity);
		int state = httpClient.executeMethod(postMethod);
		InputStream soapResponseStream = postMethod.getResponseBodyAsStream();
		InputStreamReader inputStreamReader = new InputStreamReader(soapResponseStream);
		BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
		String responseLine = "";
		String soapResponseInfo = "";
		while((responseLine = bufferedReader.readLine()) != null) {
			soapResponseInfo = soapResponseInfo + responseLine;
		}
		return soapResponseInfo;
	}
}

 

你可能感兴趣的:(java)