안 드 로 이 드 HTTP 접근 방식 두 가지

6298 단어 http
http://blog.sina.com.cn/s/blog_87216a0001014sm7.html
HttpClient 사용:
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); //      ,post  ,       Get  



        //HttpGet httpGet = new HttpGet(urlString); //Get    

          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(); //    

    }

 }

좋은 웹페이지 즐겨찾기