URL和HttpURLConnection的使用(向服务器发送请求,然后返回J2SE版)
package com.test;
/**********************************************************************
* 很完整的Demo,可以用来参考:
*
*********************************************************************/
import java.beans.XMLDecoder;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class UrlTest {
public static void main(String[] args){
???? String _url = "http://218.204.254.218:8080/richlifeApp/share/pc_getWholeCatalog";
???? URL url = null;
???? HttpURLConnection client=null;
????
???? //向服务器发关请求:
???? try {
???????? url = new URL(_url);
???????? client = (HttpURLConnection) url.openConnection();
???????? client.setRequestMethod("GET");
???????? client.setRequestProperty("pragma", "no-cache");
???????? client.setRequestProperty("Accept-Language", "UTF-8");
???????? client.setRequestProperty("Authorization","Basic MTU5ODkyMDI3NjM6U1QtMTQ2NzMtVVZUbTVMVVVRWlpOQUxkQVVrWlBGM21XbWdvcFhDVG5IUFEtMjBfXzE=");
???????? client.setDoOutput(true);
???????? client.setDoInput(true);
???????? client.connect();
???????? client.getOutputStream();
???????? OutputStream outStream = client.getOutputStream();
???????? PrintWriter out = new PrintWriter(outStream);
???????? out.print("<?xml version='1.0' encoding='UTF-8' "
???????? ?? +"standalone='no' ?><getWholeCatalog "
???????? ?? +"ownerMSISDN="15989202763"/>");
???????? out.flush();
???????? out.close();
????????
???? } catch(Exception e) {
???????? e.printStackTrace();
???? }
????
????
???? //接收服务器的返回:
???? BufferedReader in = null;
?? try {
??? in = new BufferedReader(new InputStreamReader(client
????? .getInputStream()));
??? String inputLine;
??? while ((inputLine = in.readLine()) != null) {
???? inputLine=new String(inputLine.getBytes("GBk"),"UTF-8");
???? //inputLine=new String(inputLine.getBytes("UTF-8"),"GB2312");
????
???? System.out.println(inputLine);
??? }
?? } catch (IOException e) {
??? e.printStackTrace();
?? }
??
?? System.out.println("*****************************************");
??
?? XMLDecoder d=null;
?? try {
??? try {
???? d = new XMLDecoder(new BufferedInputStream(
??????????????????????? new FileInputStream("XmlDecoderTest.xml")));
??? } catch (IOException e) {
???? // TODO Auto-generated catch block
???? e.printStackTrace();
??? }
?? } catch (Exception e1) {
??? // TODO Auto-generated catch block
??? e1.printStackTrace();
?? }
?? Object result = d.readObject();
?? d.close();
?? System.out.println(result.toString());
????
????
????
}
}