1. 程式人生 > >向伺服器端傳送請求 GET POST

向伺服器端傳送請求 GET POST

1.向伺服器端傳送請求並攜帶資料

baseURL:主機地址 真正的url在後邊+?+資料鍵值對(用&分隔多個) 問號後即查詢字串
e.g.http://192.168.1.100:8081/serverside/name?name=zhangsan&age=20

private HttpResponse httpResponse;
    private HttpEntity httpEntity;
    private String baseUrl="http://192.168.1.100:8081/serverside/name";
    String name="zs";
    String age="20";
    String url=baseUrl+"?"+"name="+name+"age="+age;
            //生成一個請求物件
            HttpGet httpGet=new HttpGet(url);
    //生成一個Http客戶端
    HttpClient httpClient = new DefaultHttpClient();
    //使用Http客戶端傳送請求物件
    InputStream inputStream=null;
    try{
        httpResponse=httpClient.execute(httpGet);
        httpEntity=httpResponse.getEntity();
        inputStream = httpEntity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String result="";
        String line="";
        while(line=read.readLine()!=null){
            result=result+line;
        }
        System.out.println(result);
    }
    catch(Exception e){
        e.printStackTrace();
    }