HttpClient作客户端,Tomcat Servlet作服务器的交互示例

转载地址:


http://blog.csdn.net/yanzi1225627/article/details/24882569


前面相继介绍了Android网络编程里的Socket传输图片HttpURLConnection,今天看HttpClient.

第一部分:JavaEE版的Eclipse配置Tomcat

【备注:开发后台服务器用Eclipse的JavaEE版最好的,但单就Tomcat来说(不写jsp之类的),本文下面的服务器方面操作在普通版的Eclipse也是可以的。我这里为了和ADT-bundle分开,特意重新安个JavaEE版的Eclipse。】

1、下载Eclipse的Tomcat插件:http://www.eclipsetotale.com/tomcatPlugin.html 将其解压得到com.sysdeo.eclipse.tomcat_3.3.0文件夹。将它复制到eclipse的plugins文件夹下。 重启Eclipse会看到上面有三个小猫,哈哈


2、下载apache-tomcat-7.0.53-windows-x86 最新到8.0了,但Eclipse支持貌似最高7.0,所以还是用7.0。解压apache-tomcat-7.0.53-windows-x86至C盘根目录,配置环境变量,新增CATALINA_HOME 路径为:C:\apache-tomcat-7.0.53 或者直接将这个变量配置到Path里都ok。  然后双击bin目录下的startup脚本,浏览器输入:http://localhost:8080/ 看到小猫表示windows上的tomcat配好了。

3、新建一个java工程,在里面选择Tomcat Project工程如图所示:


配置Tomcat和Server选项:




备注:新建工程这块也可以在Web里选择新建Dynamic Web Project,这是标准的使用Servlet、JSP等技术开发动态网站的项目,需要JavaEE版的Eclipse



第二部分:联通浏览器和Tomcat

即在浏览器输入一个网址,tomcat里返回一句话,浏览器收到并显示。之所以弄这一步一是为了测试,二是后来会发现,Android里的HttpClient就跟这个浏览器一样。

1.在WEB-INF/src文件夹下新建包名org.yanzi.testtomcat,在里面新建一个类TestTomcat继承自HttpServlet.并重写里面的doGet方法。

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
resp.setContentType("text/html;charset=utf-8");
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");


PrintWriter out = resp.getWriter();
// //用HTML格式给浏览器返回数据
// out.println("<html>");
// out.println("<head>");
// out.println("<title>Hello,Servlet!</title>");
// out.println("</head>");
// out.println("<body>");
// out.println("Hello,First Servlet!");
// out.println("</body>");
// out.println("</html>");
out.println("Hello,第一个Tomcat!!!");
out.close();
}

2.在WEB-INF文件夹下新建文件wem.xml,内容如下:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">


<web-app >
<servlet>
<servlet-name>test_yan</servlet-name>
<!-- 名字随便 -->
<servlet-class>org.yanzi.testtomcat.TestTomcat</servlet-class>
<!-- servlet类名 -->
</servlet>
<servlet-mapping>
<servlet-name>test_yan</servlet-name>
<url-pattern>/login</url-pattern>
<!-- url访问虚拟路径,最后我们就是通过工程名/login进行访问的,像这样http://127.0.0.1:8000/LoginAction/login -->
</servlet-mapping>


</web-app>

关于上面的配置注意:a. servlet-name是servlet的名字,这个名字可以随便起。只要servlet-name标签里名字一样就可以了。b. servlet-class里写包名+类名。c. url-pattern这里也是随便写的,是输入浏览器里的地址。本博文中浏览器的地址是:

http://localhost:8080/TestTomcat/login     这里的8080是端口,是在tomcat安装文件里的conf里的server.xml配置好的,用默认的就ok。除非此端口已被其他占用。 TestTomcat这里指的是工程的名字,而非类的名字。最后的“/login”跟web.xml里对应,注意后面不要再多加一个斜杠成这样"/login/", 这是解析不了的。

3. 修改conf文件夹下的tomcat-users.xml文件,在里面添加一个用户:

 <role rolename="manager"/> 
  <user username="admin" password="admin" roles="manager"/>

默认的都是全被注释掉的。

然后就可以点击eclipse上的小猫头像,开启这个servlet服务了。浏览器输入http://localhost:8080/TestTomcat/login 可以看到:


在doGet()函数里用html格式输出,即:

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
resp.setContentType("text/html;charset=utf-8");
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");


PrintWriter out = resp.getWriter();
//用HTML格式给浏览器返回数据
out.println("<html>");
out.println("<head>");
out.println("<title>Tomcat Servlet测试</title>");
out.println("</head>");
out.println("<body>");
out.println("Hello,First Servlet!");
out.println("</body>");
out.println("</html>");
out.println("Hello,第一个Tomcat!!!");
out.close();
}

看到效果:


这是因为用html格式给它设置了标题名字,并打印了一句话。这里真想吐槽一下,最初我用百度浏览器倒置了两个小时都没有出来,后来在google浏览器里一输入就ok了。真心坑爹啊。另外,如果浏览器在看视频,貌似也是出不来的。大爷的,此点么深究!!

第三部分:重写TestTomcat里的doPost()和doGet()方法。

因为我准备再手机上用doPost跟Tomcat通信,传递一个用户名和密码。Tomcat判断后再返回结果。改好后的TestTomcat.java的完整文件如下:

[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. package org.yanzi.testtomcat;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.PrintWriter;  
  5.   
  6. import javax.servlet.ServletException;  
  7. import javax.servlet.http.HttpServlet;  
  8. import javax.servlet.http.HttpServletRequest;  
  9. import javax.servlet.http.HttpServletResponse;  
  10.   
  11. public class TestTomcat extends HttpServlet {  
  12.   
  13.     private static final long serialVersionUID = 1L;  
  14.     private static final int NAME_CODE_RIGHT = 0//  
  15.     private static final int CODE_WRONG = 1;     //  
  16.     private static final int NAME_WRONG = 2;     //  
  17.   
  18.     public TestTomcat(){  
  19.   
  20.     }  
  21.     @Override  
  22.     protected void doGet(HttpServletRequest req, HttpServletResponse resp)  
  23.             throws ServletException, IOException {  
  24.         // TODO Auto-generated method stub  
  25.   
  26.         if(req == null){  
  27.             return;  
  28.         }  
  29.         resp.setContentType("text/html;charset=utf-8");  
  30.         req.setCharacterEncoding("utf-8");  
  31.         resp.setCharacterEncoding("utf-8");  
  32.         PrintWriter out = resp.getWriter();  
  33.         String name = req.getParameter("NAME");  
  34.         String code = req.getParameter("CODE");  
  35.   
  36. /*      //浏览器访问,没传递任何参数。用HTML格式给浏览器返回数据 
  37.         out.println("<html>"); 
  38.         out.println("<head>"); 
  39.         out.println("<title>Tomcat Servlet测试</title>"); 
  40.         out.println("</head>"); 
  41.         out.println("<body>"); 
  42.         out.println("Hello,哥知道你是浏览器访问的."); 
  43.         out.println("</body>"); 
  44.         out.println("</html>"); 
  45.         out.println("Hello,第一个Tomcat!!!"); 
  46.         out.close();*/  
  47.   
  48.         //手机客户端访问  
  49.         int ret = checkSubmit(name, code);  
  50.         out.print(ret);  
  51.         out.flush();  
  52.         out.close();  
  53.   
  54.     }  
  55.   
  56.     @Override  
  57.     protected void doPost(HttpServletRequest req, HttpServletResponse resp)  
  58.             throws ServletException, IOException {  
  59.         // TODO Auto-generated method stub  
  60.         if(req == null){  
  61.             return;  
  62.         }  
  63.   
  64.         resp.setContentType("text/html;charset=utf-8");  
  65.         req.setCharacterEncoding("utf-8");  
  66.         resp.setCharacterEncoding("utf-8");  
  67.   
  68.         PrintWriter out = resp.getWriter();  
  69.         String name = req.getParameter("NAME");  
  70.         String code = req.getParameter("CODE");  
  71.   
  72.         int ret = checkSubmit(name, code);  
  73.         out.print(ret);  
  74.         out.flush();  
  75.         out.close();  
  76.     }  
  77.   
  78.     /** 
  79.      * 判断登录名和密码 
  80.      * @param name 
  81.      * @param code 
  82.      * @return 
  83.      */  
  84.     private int checkSubmit(String name, String code){  
  85.         int ret = -2;  
  86.         if(name.equals("admin")){  
  87.             if(code.equals("123")){  
  88.                 ret = NAME_CODE_RIGHT;  
  89.             }else{  
  90.                 ret = CODE_WRONG;  
  91.             }  
  92.         }else{  
  93.             ret = NAME_WRONG;  
  94.         }  
  95.         return ret;  
  96.     }  
  97.   
  98.   
  99. }  

第四步: Android客户端的开发,这里我弄两个按钮分别对应HttpPost和HttpGet两种方式跟服务器通讯。下面是个ScrollView显示服务器回传结果.效果如下所示:


AndroidManifest.xml里加权限:  <uses-permission android:name="android.permission.INTERNET"/>


activity_main.xml的内容:

[html]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:paddingBottom="@dimen/activity_vertical_margin"  
  6.     android:paddingLeft="@dimen/activity_horizontal_margin"  
  7.     android:paddingRight="@dimen/activity_horizontal_margin"  
  8.     android:paddingTop="@dimen/activity_vertical_margin"  
  9.     tools:context=".MainActivity" >  
  10.   
  11.     <EditText  
  12.         android:id="@+id/edit_name"  
  13.         android:layout_width="match_parent"  
  14.         android:layout_height="wrap_content"  
  15.         android:hint="输入用户名" />  
  16.   
  17.     <EditText  
  18.         android:id="@+id/edit_code"  
  19.         android:layout_width="match_parent"  
  20.         android:layout_height="wrap_content"  
  21.         android:layout_below="@id/edit_name"  
  22.         android:hint="输入密码" />  
  23.   
  24.     <LinearLayout  
  25.         android:id="@+id/layout_btn"  
  26.         android:layout_width="match_parent"  
  27.         android:layout_height="wrap_content"  
  28.         android:layout_centerInParent="true"  
  29.         android:orientation="horizontal" >  
  30.   
  31.         <Button  
  32.             android:id="@+id/btn_submit_post"  
  33.             android:layout_width="0dip"  
  34.             android:layout_height="wrap_content"  
  35.             android:layout_weight="1"  
  36.             android:gravity="center"  
  37.             android:text="POST登录 " />  
  38.   
  39.         <Button  
  40.             android:id="@+id/btn_submit_get"  
  41.             android:layout_width="0dip"  
  42.             android:layout_height="wrap_content"  
  43.             android:layout_weight="1"  
  44.             android:gravity="center"  
  45.             android:text="GET登录 " />  
  46.     </LinearLayout>  
  47.   
  48.     <ScrollView  
  49.         android:id="@+id/info_scroll_view"  
  50.         android:layout_width="match_parent"  
  51.         android:layout_height="wrap_content"  
  52.         android:layout_below="@id/layout_btn" >  
  53.   
  54.         <TextView  
  55.             android:id="@+id/tv_info"  
  56.             android:layout_width="wrap_content"  
  57.             android:layout_height="wrap_content"  
  58.             android:text="结果显示........." />  
  59.     </ScrollView>  
  60.   
  61. </RelativeLayout>  

MainActivity.java里的内容:

[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. package org.yanzi.testtomecat;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.UnsupportedEncodingException;  
  5. import java.util.ArrayList;  
  6. import java.util.List;  
  7.   
  8. import org.apache.http.HttpResponse;  
  9. import org.apache.http.HttpStatus;  
  10. import org.apache.http.client.ClientProtocolException;  
  11. import org.apache.http.client.HttpClient;  
  12. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  13. import org.apache.http.client.methods.HttpGet;  
  14. import org.apache.http.client.methods.HttpPost;  
  15. import org.apache.http.conn.params.ConnManagerParams;  
  16. import org.apache.http.impl.client.DefaultHttpClient;  
  17. import org.apache.http.impl.conn.DefaultClientConnection;  
  18. import org.apache.http.message.BasicNameValuePair;  
  19. import org.apache.http.params.BasicHttpParams;  
  20. import org.apache.http.params.HttpConnectionParams;  
  21. import org.apache.http.params.HttpParams;  
  22. import org.apache.http.protocol.HTTP;  
  23. import org.apache.http.util.EntityUtils;  
  24.   
  25. import android.app.Activity;  
  26. import android.os.AsyncTask;  
  27. import android.os.Bundle;  
  28. import android.view.Menu;  
  29. import android.view.View;  
  30. import android.view.View.OnClickListener;  
  31. import android.widget.Button;  
  32. import android.widget.EditText;  
  33. import android.widget.ScrollView;  
  34. import android.widget.TextView;  
  35.   
  36. public class MainActivity extends Activity {  
  37.     public static final String URL = "http://192.168.16.8:8080/TestTomcat/login";  
  38.     Button submitBtnPost = null;  
  39.     Button submitBtnGet = null;  
  40.     TextView infoTextView = null;  
  41.     EditText nameEdit = null;  
  42.     EditText codeEdit = null;  
  43.     ScrollView scrollView = null;  
  44.     boolean isPost = true//默认采取post登录方式  
  45.       
  46.     @Override  
  47.     protected void onCreate(Bundle savedInstanceState) {  
  48.         super.onCreate(savedInstanceState);  
  49.         setContentView(R.layout.activity_main);  
  50.         scrollView = (ScrollView)findViewById(R.id.info_scroll_view);  
  51.         submitBtnPost = (Button)findViewById(R.id.btn_submit_post);  
  52.         submitBtnGet = (Button)findViewById(R.id.btn_submit_get);  
  53.         infoTextView = (TextView)findViewById(R.id.tv_info);  
  54.         nameEdit = (EditText)findViewById(R.id.edit_name);  
  55.         codeEdit = (EditText)findViewById(R.id.edit_code);  
  56.         submitBtnPost.setOnClickListener(new View.OnClickListener() {  
  57.               
  58.             @Override  
  59.             public void onClick(View v) {  
  60.                 // TODO Auto-generated method stub  
  61.                 isPost = true;  
  62.                 new SubmitAsyncTask().execute(URL);  
  63.             }  
  64.         });  
  65.         submitBtnGet.setOnClickListener(new View.OnClickListener() {  
  66.               
  67.             @Override  
  68.             public void onClick(View v) {  
  69.                 // TODO Auto-generated method stub  
  70.                 isPost = false;  
  71.                 new SubmitAsyncTask().execute(URL);  
  72.             }  
  73.         });  
  74.     }  
  75.       
  76.   
  77.   
  78.     @Override  
  79.     public boolean onCreateOptionsMenu(Menu menu) {  
  80.         // Inflate the menu; this adds items to the action bar if it is present.  
  81.         getMenuInflater().inflate(R.menu.main, menu);  
  82.         return true;  
  83.     }  
  84.     public class SubmitAsyncTask extends AsyncTask<String, Void, String>{  
  85.         String info = "";  
  86.         @Override  
  87.         protected String doInBackground(String... params) {  
  88.             // TODO Auto-generated method stub  
  89.             String url = params[0];  
  90.             String reps = "";  
  91.             if(isPost){  
  92.                 info = "HttpPost返回结果: ";  
  93.                 reps = doPost(url);  
  94.             }else{  
  95.                 info = "HttpGet返回结果: ";  
  96.                 reps = doGet(url);    
  97.             }  
  98.             return reps;  
  99.         }  
  100.   
  101.         @Override  
  102.         protected void onPostExecute(String result) {  
  103.             // TODO Auto-generated method stub  
  104.             infoTextView.append("\n" + info + result +"\n");  
  105.             String res = result.trim();  
  106.             if(res.equals("0")){  
  107.                 info = "验证通过.....";  
  108.             }else if(res.equals("1")){  
  109.                 info = "密码错误.....";  
  110.             }else if(res.equals("2")){  
  111.                 info = "用户名错误.....";  
  112.             }else if(res.equals("-1")){  
  113.                 info = "返回结果异常!";  
  114.             }  
  115.             infoTextView.append(info + "\n");  
  116.             scrollView.fullScroll(ScrollView.FOCUS_DOWN);  
  117.             super.onPostExecute(result);  
  118.         }  
  119.           
  120.   
  121.   
  122.     }  
  123.     private String doGet(String url){  
  124.         String responseStr = "";  
  125.         try {  
  126.             String name = nameEdit.getText().toString().trim();  
  127.             String code = codeEdit.getText().toString().trim();  
  128.             String getUrl = URL + "?NAME=" + name+"&"+"CODE=" + code;         
  129.               
  130.             HttpGet httpRequest = new HttpGet(getUrl);  
  131.             HttpParams params = new BasicHttpParams();  
  132.             ConnManagerParams.setTimeout(params, 1000);  
  133.             HttpConnectionParams.setConnectionTimeout(params, 3000);  
  134.             HttpConnectionParams.setSoTimeout(params, 5000);  
  135.             httpRequest.setParams(params);  
  136.   
  137.             HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);  
  138.         final int ret = httpResponse.getStatusLine().getStatusCode();  
  139.         if(ret == HttpStatus.SC_OK){  
  140.             responseStr = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);  
  141.         }else{  
  142.             responseStr = "-1";  
  143.         }  
  144.         } catch (ClientProtocolException e) {  
  145.             // TODO Auto-generated catch block  
  146.             e.printStackTrace();  
  147.         } catch (IOException e) {  
  148.             // TODO Auto-generated catch block  
  149.             e.printStackTrace();  
  150.         }  
  151.           
  152.         return responseStr;  
  153.     }  
  154.       
  155.     /** 
  156.      * 用Post方式跟服务器传递数据 
  157.      * @param url 
  158.      * @return 
  159.      */  
  160.     private String doPost(String url){  
  161.         String responseStr = "";  
  162.         try {  
  163.             HttpPost httpRequest = new HttpPost(url);  
  164.             HttpParams params = new BasicHttpParams();  
  165.             ConnManagerParams.setTimeout(params, 1000); //从连接池中获取连接的超时时间  
  166.             HttpConnectionParams.setConnectionTimeout(params, 3000);//通过网络与服务器建立连接的超时时间  
  167.             HttpConnectionParams.setSoTimeout(params, 5000);//读响应数据的超时时间  
  168.             httpRequest.setParams(params);  
  169.             //下面开始跟服务器传递数据,使用BasicNameValuePair  
  170.             List<BasicNameValuePair> paramsList = new ArrayList<BasicNameValuePair>();  
  171.             String name = nameEdit.getText().toString().trim();  
  172.             String code = codeEdit.getText().toString().trim();  
  173.             paramsList.add(new BasicNameValuePair("NAME", name));  
  174.             paramsList.add(new BasicNameValuePair("CODE", code));  
  175.             UrlEncodedFormEntity mUrlEncodeFormEntity = new UrlEncodedFormEntity(paramsList, HTTP.UTF_8);  
  176.             httpRequest.setEntity(mUrlEncodeFormEntity);  
  177.             HttpClient httpClient = new DefaultHttpClient();  
  178.             HttpResponse httpResponse = httpClient.execute(httpRequest);  
  179.             final int ret = httpResponse.getStatusLine().getStatusCode();  
  180.             if(ret == HttpStatus.SC_OK){  
  181.                 responseStr = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);  
  182.             }else{  
  183.                 responseStr = "-1";  
  184.             }  
  185.   
  186.         } catch (UnsupportedEncodingException e) {  
  187.             // TODO Auto-generated catch block  
  188.             e.printStackTrace();  
  189.         } catch (ClientProtocolException e) {  
  190.             // TODO Auto-generated catch block  
  191.             e.printStackTrace();  
  192.         } catch (IOException e) {  
  193.             // TODO Auto-generated catch block  
  194.             e.printStackTrace();  
  195.         }  
  196.   
  197.         return responseStr;  
  198.     }  
  199.   
  200. }  

要点注释:

1、核心在doGet()和doPost()两个函数里,可以看到用get方式比用post传递参数更方便,可以直接写到url里。使用get方式时传递数据在url里写的:

String name = nameEdit.getText().toString().trim();
String code = codeEdit.getText().toString().trim();
String getUrl = URL + "?NAME=" + name+"&"+"CODE=" + code;

post方式时是用BasicNameValuePair来弄的。其他流程都差不多。首先new一个HttpGet或HttpPost,然后设参数,共设三个,作用注释里有。然后设参数,传数据,通过HttpResponse httpResponse = httpClient.execute(httpRequest);得到返回结果。

2、如果在Tomcat里使用的是out.println(),则再解析数据时需要再得到的String上trim()一下,否则会错。

3、Android客户端URL地址为:

public static final String URL = "http://192.168.16.8:8080/TestTomcat/login";

这里的IP就是电脑的IP加端口号就ok。


当然这仅是个最基本的示例,遗留问题:

1.JSON传递数据

2.每次链接都开一个DefaultHttpClient很不科学。


参考: 

http://blog.chinaunix.net/uid-25799257-id-3774015.html

http://blog.chinaunix.net/uid-25799257-id-3774047.html


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 好的,下面是一个使用 HttpClient 发送 HTTP GET 请求的简单代码示例: ```java import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class HttpClientExample { public static void main(String[] args) throws Exception { // 创建 HttpClient 实例 CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建 HttpGet 实例 HttpGet httpGet = new HttpGet("http://www.example.com"); // 发送 GET 请求 CloseableHttpResponse response = httpClient.execute(httpGet); // 获取响应状态码 int statusCode = response.getStatusLine().getStatusCode(); // 获取响应内容 String content = EntityUtils.toString(response.getEntity()); // 关闭响应 response.close(); // 关闭 HttpClient httpClient.close(); } } ``` 在这个例子中,我们使用 HttpClient 的默认配置创建了一个 HttpClient 实例,并使用 HttpGet 类创建了一个 GET 请求。然后,我们调用 HttpClient 的 execute() 方法执行请求并获取响应。最后,我们关闭响应并关闭 HttpClient。 注意: 在这个例子中,我们使用了 Apache HttpComponents 的 HttpClient 类。这是一个功能强大且流行的 HTTP 客户端库,但是它也有其他的选择,如 Java 11 中的 HttpClient API。 ### 回答2: HttpClient是一个开源的第三方Java库,用于网络通信和HTTP操。通过HttpClient,我们可以方便地发送HTTP请求和接收HTTP响应,实现与Web服务器交互。 以下是一个简单的Java Httpclient代码示例: ```java import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class HttpClientExample { public static void main(String[] args) { CloseableHttpClient httpClient = HttpClients.createDefault(); try { // 创建HttpGet请求 HttpGet httpGet = new HttpGet("http://example.com"); // 发送请求并获取响应 CloseableHttpResponse response = httpClient.execute(httpGet); try { // 打印响应状态码 System.out.println(response.getStatusLine()); // 获取响应内容 HttpEntity entity = response.getEntity(); String content = EntityUtils.toString(entity); System.out.println(content); } finally { // 关闭响应 response.close(); } } catch (Exception e) { e.printStackTrace(); } finally { try { // 关闭HttpClient httpClient.close(); } catch (Exception e) { e.printStackTrace(); } } } } ``` 以上示例使用HttpClient发送一个GET请求至"http://example.com",并打印响应状态码和内容。 要使用HttpClient,我们首先需要创建一个CloseableHttpClient实例。然后,我们可以创建HttpGet、HttpPost等请求对象,并设置需要的请求参数。最后,调用httpClient.execute方法发送请求并获取响应。在使用完响应后,我们需要手动关闭CloseableHttpResponse和CloseableHttpClientHttpClient还提供了丰富的API,我们可以设置请求头、处理Cookie、设置代理等。此外,还有更高级的功能,如连接池管理、重试机制等。 HttpClient是Java中使用广泛的网络通信库,可用于各种HTTP相关的任务,如爬虫、HTTP客户端等。它简化了与Web服务器的通信,并提供了丰富的功能和灵活性。 ### 回答3: 以下是一个简单的Java HttpClient代码示例: ```java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; public class HttpClientExample { public static void main(String[] args) { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet("http://example.com"); try (CloseableHttpResponse response = httpClient.execute(httpGet)) { HttpEntity entity = response.getEntity(); BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } } } ``` 这个示例使用了Apache HttpComponents库中的HttpClient,通过发送GET请求来获取指定URL的响应数据。首先,我们创建一个CloseableHttpClient实例,然后使用HttpGet对象来定义GET请求的URL。接下来,通过httpClient的execute方法发送请求并获取响应。我们从响应中获取HttpEntity实体,并使用InputStreamReader来读取其内容。最后,我们将读取的内容逐行打印出来。 请注意,这只是一个基本的示例,并未包含异常处理等边缘情况的处理。在实际应用中,你可能需要更全面和严谨的代码来处理各种可能的情况和错误。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值