web中间件 java调用http接口示例
package Test;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;

public class TestHttpSend {

	public static void main(String[] args) throws Exception {
		testPostSend("httpPostn测试换行");
	}

	public static void testGetSend(String text) {
		String urlStr = "http://127.0.0.1:8060/send?password=1&text=[content]&recipient=18310409073&encoding=U";
		URL url;
		try {
			urlStr = urlStr.replace("[content]", URLEncoder.encode(text, "UTF-8"));
			System.out.println(urlStr);
			url = new URL(urlStr);
			URLConnection URLconnection = url.openConnection();
			HttpURLConnection httpConnection = (HttpURLConnection) URLconnection;
			int responseCode = httpConnection.getResponseCode();
			if (responseCode == HttpURLConnection.HTTP_OK) {
				InputStream urlStream = httpConnection.getInputStream();
				BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlStream));
				String sCurrentLine = "";
				String sTotalString = "";
				while ((sCurrentLine = bufferedReader.readLine()) != null) {
					sTotalString += sCurrentLine;
				}
				System.err.println(URLDecoder.decode(sTotalString, "UTF-8"));
				if (sTotalString.equals("OK")) {
				} else {
				}
			} else {
				System.err.println("调用失败,返回错误码"+responseCode);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch blockeb
			e.printStackTrace();
		}

	}

	public static void testPostSend(String text) throws Exception {
		String urlStr = "http://127.0.0.1:8060/send";
		URL url = new URL(urlStr);
		String queryString = "password=1&text=[content]&recipient=18310409073&encoding=U";
		queryString = queryString.replace("[content]",text);
		HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
		httpConnection.setRequestMethod("POST");
		httpConnection.setConnectTimeout(0);
		httpConnection.setInstanceFollowRedirects(true);
		httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		httpConnection.setDefaultUseCaches(false);
		httpConnection.setDoOutput(true);
		PrintWriter out = new PrintWriter(httpConnection.getOutputStream());
		out.print(queryString);
		out.close();
		int responseCode = httpConnection.getResponseCode();
		if (responseCode == HttpURLConnection.HTTP_OK) {
			InputStream urlStream = httpConnection.getInputStream();
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlStream));
			String sCurrentLine = "";
			while ((sCurrentLine = bufferedReader.readLine()) != null) {
				System.out.println(sCurrentLine);
			}
		}
	}
}

附件:
  • 这个文档对您有帮助的吗?
  • |