1. 程式人生 > >HttpClient GET和POST請求

HttpClient GET和POST請求

pri execute public methods gre col esp odt stringbu

package com.rogue.hclient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.RequestEntity; import org.apache.commons.httpclient.methods.StringRequestEntity; /** * 測試HttpClient功能 * @author djoker * */ public class HClientTest { HttpClient client = new HttpClient();
//get功能測試 public void getTest(){ String uri = "http://172.16.100.20/cgi-bin/ht.cgi?method=getMethodTest"; GetMethod method = new GetMethod(uri); try { int code = client.executeMethod(method); System.out.println(code); if(200 == code){
// StringBuffer sb = new StringBuffer(); // sb.append(method.getResponseBodyAsString()); //不推薦使用,會有警告,如果讀取的內容過多,會導致超過最大讀取值 // System.out.println(sb.toString()); InputStream is = method.getResponseBodyAsStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8")); String line = null; while((line = br.readLine()) != null){ System.out.println(line); } } } catch (HttpException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //POST測試 public void postTest(){ String uri = "http://172.16.100.20/cgi-bin/ht.cgi"; String content = "method=PostMethod&paramer=paramer"; //參數 PostMethod method = new PostMethod(uri); RequestEntity requestEntity = new StringRequestEntity(content); //字符串請求參數 method.setRequestEntity(requestEntity); //設置請求參數 try { int code = client.executeMethod(method); System.out.println(code); if(200 == code){ InputStream is = method.getResponseBodyAsStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8")); String line = null; while((line = br.readLine()) != null){ System.out.println(line); } } } catch (HttpException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[] args){ HClientTest hct = new HClientTest(); hct.getTest(); System.out.println("--------"); hct.postTest(); } }

HttpClient GET和POST請求