使用HttpURLConnection發送get和post請求

轉載請註明出處:http://blog.csdn.net/forwardyzk/article/details/45364463

我們在開發的使用,直接使用的開源框架,例如:Xutil,Volley開源框架直接訪問網絡,但是我們也需要知道其中的一些知識,瞭解一下怎樣訪問網絡的。下面我們模擬以下客戶端和服務端,看看post和get請求。


首先我們開發一下客戶端:



1.首先自定義線程,開啓get請求。

public class GetThread extends Thread {
    private String name;
    private String age;
    private TextView show_content;
    private String url = "";
    private Handler handler = new Handler();

    public GetThread(String url, TextView show_content) {
        this.show_content = show_content;
        this.url = url;
    }

    public GetThread(String url, String name, String age, TextView show_content) {
        this.name = name;
        this.age = age;
        this.show_content = show_content;
        this.url = url;
    }

    @Override
    public void run() {
        super.run();
        getRun();
    }

    private void getRun() {
        if (TextUtils.isEmpty(url)) {
            throw new NullPointerException("please ensure url is not equals  null ");
        }
        BufferedReader bufferedReader = null;
        try {
            if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(age)) {
                url = url + "?name=" + URLEncoder.encode(name, "utf-8") + "&age=" + URLEncoder.encode(age, "utf-8");
            }
            URL httpUrl = new URL(url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) httpUrl.openConnection();
            httpURLConnection.setReadTimeout(5000);
            httpURLConnection.setRequestMethod("GET");
            //設置請求頭header
            httpURLConnection.setRequestProperty("test-header","get-header-value");
            //獲取內容
            InputStream inputStream = httpURLConnection.getInputStream();
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            final StringBuffer stringBuffer = new StringBuffer();
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuffer.append(line);
            }
            handler.post(new Runnable() {
                @Override
                public void run() {
                    show_content.setText(stringBuffer.toString());
                }
            });
        } catch (Exception e) {

        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}


對於Get請求,請求參數是拼接在Url上的。例如:http://xxxx?name=zhangsan&age=20

httpURLConnection.setReadTimeout(5000);設置超時時間

httpURLConnection.setRequestMethod("GET");設置請求方法

httpURLConnection.setRequestProperty("test-header","get-header-value");設置請求頭header

獲取從服務器傳回來的內容

InputStream inputStream = httpURLConnection.getInputStream();

講InputStream 轉換成BufferedReader,便於操作流

將流中的數據存入到了StringBuffer中,最後設置給展示內容的TextView上。

最後要記得關閉流。


2.自定義PostThread線程,開啓Post請求

public class PostThread extends Thread {
    private String name;
    private String age;
    private TextView show_content;
    private String url = "";
    private Handler handler = new Handler();

    public PostThread(String url, TextView show_content) {
        this.show_content = show_content;
        this.url = url;
    }

    public PostThread(String url, String name, String age, TextView show_content) {
        this.name = name;
        this.age = age;
        this.show_content = show_content;
        this.url = url;
    }

    @Override
    public void run() {
        super.run();
        getRun();
    }

    private void getRun() {
//        Properties p=System.getProperties();
//        p.list(System.out);
        if (TextUtils.isEmpty(url)) {
            throw new NullPointerException("please ensure url is not equals  null ");
        }
        BufferedReader bufferedReader = null;
        try {
            URL httpUrl = new URL(url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) httpUrl.openConnection();
            //設置請求頭header
            httpURLConnection.setRequestProperty("test-header","post-header-value");
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setReadTimeout(5000);

            //設置請求參數
            if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(age)) {
                OutputStream outputStream = httpURLConnection.getOutputStream();
//                String params="name="+ URLEncoder.encode(name, "utf-8")+"&age="+ URLEncoder.encode(age, "utf-8");
                String params="name="+ name+"&age="+ age;
                outputStream.write(params.getBytes());
            }

            //獲取內容
            InputStream inputStream = httpURLConnection.getInputStream();
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            final StringBuffer stringBuffer = new StringBuffer();
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuffer.append(line);
            }
            handler.post(new Runnable() {
                @Override
                public void run() {
                    show_content.setText(stringBuffer.toString());
                }
            });
        } catch (Exception e) {

        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}


對於Post請求和Get請求有不同的地方

get請求是把請求參數拼接到Url中,可以在url中看到。而post請求不把請求參數放在了請求體中。

給Post設置請求參數

OutputStream outputStream = httpURLConnection.getOutputStream();獲取請求連接的寫入流

String params="name="+ name+"&age="+ age;拼接請求參數字符串

outputStream.write(params.getBytes());講請求參數寫入到寫入流中

其他的地方和get請求是一樣的。


3.在MainActivity中開啓線程,併發送get和Post請求

/**
     * get request
     */
    private void getSubmit() {
        String url = AddressUtil.LOGIN_URL;
        String name = ed_name.getText().toString().trim();
        String age = ed_age.getText().toString().trim();
        new GetThread(url,name,age ,show_content).start();
    }

    /**
     * post request
     */
    private void postSubmot() {
        String url = AddressUtil.LOGIN_URL;
        String name = ed_name.getText().toString().trim();
        String age = ed_age.getText().toString().trim();
        new PostThread(url,name,age ,show_content).start();
    }


開啓GetThread線程,發送get請求

第一個參數:請求地址

第二個參數:登錄的名字,寫入到了請求參數中

第三個參數:登錄的年齡,寫入到了請求參數中

第四個參數:展示服務器返回內容的展示的TextView


public class AddressUtil {
    public final  static  String LOCALHOST="http://10.2.52.19:8080";
    public final  static  String LOGIN_URL=LOCALHOST+"/HttpServerDemo/servlet/LoginServlet";

}


地址模擬服務器的地址。下面我們就看一看服務器是怎樣運作的。



3.開發模擬的服務器

新建LoginServlet

public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		// 獲取請求頭
		String header = request.getHeader("test-header");
		if (header != null && !header.equals(""))
			System.out.println("test-header=" + header);
		// 獲取請求參數
		String name = request.getParameter("name");
		String age = request.getParameter("age");
		// 打印流
		PrintWriter out = response.getWriter();
		// 拼接返回給服務端的內容,並且輸出
		if (name == null || name.equals("") || age == null || age.equals("")) {
			out.println("{'result':'1','error':'name and age is null'");
		} else {
			out.println("{'result':'0','user':{'name':'"
					+ new String(name.getBytes("iso-8859-1"), "utf-8")
					+ "','age':'"
					+ new String(age.getBytes("iso-8859-1"), "utf-8") + "'}}");
			System.out.println("name="
					+ new String(name.getBytes("iso-8859-1"), "utf-8"));
			System.out.println("age="
					+ new String(age.getBytes("iso-8859-1"), "utf-8"));
		}

		out.flush();
		out.close();
	}



在index.jsp中寫登錄的界面




3.1代碼:Post請求




顯示下面的截圖,表示post請求成功



3.2 Get請求




如果限制的內容和圖片是一樣,標識get請求已經成功訪問。



4.下面使用手機端的App訪問服務端

 使用手機端訪問服務端,要把localhost轉換成IP地址

請求地址的拼接

public class AddressUtil {
    public final  static  String LOCALHOST="http://10.2.52.19:8080";
    public final  static  String LOGIN_URL=LOCALHOST+"/HttpServerDemo/servlet/LoginServlet";

}

4.1Get請求

代碼請求

/**
     * get request
     */
    private void getSubmit() {
        String url = AddressUtil.LOGIN_URL;
        String name = ed_name.getText().toString().trim();
        String age = ed_age.getText().toString().trim();
        new GetThread(url,name,age ,show_content).start();
    }

請求結果



4.2 Post請求

代碼請求

 /**
     * post request
     */
    private void postSubmot() {
        String url = AddressUtil.LOGIN_URL;
        String name = ed_name.getText().toString().trim();
        String age = ed_age.getText().toString().trim();
        new PostThread(url,name,age ,show_content).start();
    }


請求結果:


這樣客服端和服務端的開發,get和post請求已經成功。


客戶端源碼下載:http://download.csdn.net/detail/forwardyzk/8645171

服務端源碼下載:http://download.csdn.net/detail/forwardyzk/8645181


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章