get
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.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
public class H_client_get {
public static void main(String[] args) throws IOException {
// new類對象
HttpClient client = new HttpClient();
// 使用 GET 方法 與URL服務器進行交互
// HttpMethod method = new GetMethod("http://192.168.111.128/bak/[email protected]&password=1234567&re_password=1234567&username=admin&nickname=管理員");
HttpMethod method = new GetMethod("http://192.168.111.128/bak/login.php?username=");
// 使用 GET 方法 ,實行與url服務器連接
client.executeMethod(method);
// 數據流輸出
// method.getResponseBodyAsStream 創建字節流對象爲inputStream
InputStream inputStream = method.getResponseBodyAsStream();
// InputStreamReader(inputStream)字節流轉換成字符流 BufferedReader封裝成帶有緩衝的字符流對象了
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
// StringBuffer是字符串變量,它的對象是可以擴充和修改的 創建一個空的StringBuffer類的對象
StringBuffer stringBuffer = new StringBuffer();
// 定義字符串常量
String str= "";
// br字符流賦值給str字符串常量 str不等於空 按行輸出
while((str = br.readLine()) != null){
// StringBuffer 是字符串變量,它的對象是可以擴充和修改的 將str數據賦予 stringBuffer
stringBuffer .append(str );
}
// 按照字符串循環輸出stringBuffer
System.out.println(stringBuffer.toString());
// 關閉method 的 httpclient連接
method.releaseConnection();
}
}
post
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.*;
public class H_client_post {
public static void main(String[] args) throws IOException {
HttpClient client = new HttpClient();
PostMethod method = new PostMethod("http://192.168.111.128/bak/login_post.php");
//表單域的值,既post傳入的key=value
NameValuePair[] date = { new NameValuePair("username","admin"),new NameValuePair("password","123457")};
//method使用表單閾值
method.setRequestBody(date);
//提交表單
client.executeMethod(method);
//字符流轉字節流 循環輸出,同get解釋
InputStream inputStream = method.getResponseBodyAsStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
StringBuffer stringBuffer = new StringBuffer();
String str= "";
while((str = br.readLine()) != null){
stringBuffer .append(str );
}
System.out.println(stringBuffer.toString());
method.releaseConnection();
}
}
beginner自己保存,瀏覽者可指出錯誤