HTTP 接口 一般比较常用的 类 有HTTPClient,及URLConnection,GET方式发送报文只能设置包头 然后将要发送的报文放入 要访问的URL中,如果用URLConnection的方式去发送报文,即便是在 URLConection中设置
httpUrlConnection.setRequestMethod("GET");
时.若在中写入 httpUrlConnection.getOutputStream().writeObject(new String("我是测试数据"));非URL之外的码流时,用抓包工具分析时会自动转化为POST方式,所以用URLConnection用GET方式发送报文不靠谱.所以
要用HTTP接口GET方式最好使用HTTPClient方式.
- public static String getDoGetURL(String url, String charset) throws Exception {
- HttpClient client = new HttpClient();
- GetMethod method1 = new GetMethod(url);
- if ( null == url || !url.startsWith( "http" )) {
- throw new Exception( "请求地址格式不对" );
- }
- // 设置请求的编码方式
- if ( null != charset) {
- method1.addRequestHeader( "Content-Type" ,
- "application/x-www-form-urlencoded; charset=" + charset);
- } else {
- method1.addRequestHeader( "Content-Type" ,
- "application/x-www-form-urlencoded; charset=" + "utf-8" );
- }
- int statusCode = client.executeMethod(method1);
- if (statusCode != HttpStatus.SC_OK) { // 打印服务器返回的状态
- System.out.println( "Method failed: " + method1.getStatusLine());
- }
- // 返回响应消息
- byte[] responseBody = method1.getResponseBodyAsString().getBytes(method1.getResponseCharSet());
- // 在返回响应消息使用编码(utf-8或gb2312)
- String response = new String(responseBody, "utf-8" );
- System.out.println( "------------------response:" +response);
- // 释放连接
- method1.releaseConnection();
- return response;
- }

本文介绍如何使用 HTTPClient 实现 GET 请求,并提供了一个示例代码。文章对比了使用 URLConnection 和 HTTPClient 的区别,强调了正确设置请求参数的重要性。
6722

被折叠的 条评论
为什么被折叠?



