HTTPアクセスの2つの方法(HttpClientとHttpURLConnection)

2812 ワード

直接コード
 
Http Clientを使う
NameValuePair nameValuePair1 = new BasicNameValuePair("name", "yang");
NameValuePair nameValuePair2 = new BasicNameValuePair("pwd","123123");
List nameValuePairs = new ArrayList();
nameValuePairs.add(nameValuePair1);
nameValuePairs.add(nameValuePair2);
String validateURL = "http://10.0.2.2:8080/testhttp1/TestServlet";

try {

        HttpParams httpParams = new BasicHttpParams();

        HttpConnectionParams.setConnectionTimeout(httpParams,5000); //       5 

        HttpClient client = new DefaultHttpClient(httpParams); //     http         

        HttpPost httpPost = new HttpPost(urlString); //      

          if (nameValuePairs!=null && nameValuePairs.size()!=0) {
              //             HttpEntity   
              httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8));
           }

        HttpResponse httpResponse = client.execute(httpPost); //          

          //           
          if (httpResponse.getStatusLine().getStatusCode() != 200) {
             System.out.println("      !!!!");

             return false;
           }

        HttpEntity entity = httpResponse.getEntity(); //          
        inputStream = entity.getContent();  //               (       )
        //               (         )
        // String strResult = EntityUtils.toString(entity); 

      } catch (Exception e) {
   System.out.println("    !");
  }
 
HttpURLConnectionを使う
String validateURL="http://10.0.2.2:8080/testhttp1/TestServlet?name=yang&pwd=123123";

try {

       URL url = new URL(validateUrl); //  URL  

       //    URLConnection  ,    URL           

       HttpURLConnection conn = (HttpURLConnection) url.openConnection();

       conn.setConnectTimeout(5000); //       5 

       conn.setRequestMethod("GET"); //      

       conn.connect(); //            

       //            

       DataInputStream dis = new DataInputStream(conn.getInputStream());  

      //           

        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
           System.out.println("      !!!!");

           return  false;
       }

} catch (Exception e) {
   e.printStackTrace();
   System.out.println("    !");
  } finally {
    if (conn != null) {
     conn.disconnect(); //    
    }
 }