HttpClient几种请求方法示例

HttpClient使用总结
1.Get

	public static String getResultWithGet(HttpServletRequest request, String url) throws Exception{
		String result =  null;
		HttpClient client =getClient(); 
		try{
			HttpGet get = new HttpGet(url);
			HttpResponse response = client.execute(get); 
			result = getResponseBodyAsString(response);
		}finally{
			client.getConnectionManager().shutdown();  
		}
		return result;
	}


2、Post

public static String getResultWithPost(HttpServletRequest request, String url) throws Exception{
		String json = null;
		HttpClient client =getClient(); 
		try{
			HttpPost post = new HttpPost(url);
			@SuppressWarnings("unchecked")
			Map<String, String[]> map = request.getParameterMap();
			Set<String> keySet = map.keySet();
			JSONObject jo = new JSONObject();
			for(String s : keySet){
				if(!"".equals(map.get(s)[0])){
					jo.element(s, map.get(s)[0]);
				}
				
			}
			StringEntity reqEntity = new StringEntity(jo.toString(),"UTF-8");
			reqEntity.setContentType("application/json");
			post.setEntity(reqEntity);
			HttpResponse response = client.execute(post);
			json = getResponseBodyAsString(response);
		}finally{
			client.getConnectionManager().shutdown();  
		}
		return json;
	}


3、Put

public static String getResultWithPut(HttpServletRequest request, String url) throws Exception{
		String json = null;
		HttpClient client =getClient(); 
		try{
			HttpPut put = new HttpPut(url);
			@SuppressWarnings("unchecked")
			Map<String, String[]> map = request.getParameterMap();
			Set<String> keySet = map.keySet();
			JSONObject jo = new JSONObject();
			for(String s : keySet){
				if(!"".equals(map.get(s)[0])){
					jo.element(s, map.get(s)[0]);
				}
				
			}
			StringEntity reqEntity = new StringEntity(jo.toString(),"UTF-8");
			reqEntity.setContentType("application/json");
			put.setEntity(reqEntity);
			HttpResponse response = client.execute(put);
			json = getResponseBodyAsString(response);
		}finally{
			client.getConnectionManager().shutdown();  
		}
		return json;
	}


4、Delete

public static String getResultWithDelete(HttpServletRequest request, String url) throws Exception{
		String result = null;
		HttpClient client =getClient(); 
		try{
			HttpDelete delete = new HttpDelete(url);
			HttpResponse response  = client.execute(delete);
			result = getResponseBodyAsString(response);
		}finally{
			client.getConnectionManager().shutdown();  
		}
		return result;
	}


5、getResponseBodyAsString

public static String getResponseBodyAsString(HttpResponse response) throws Exception {
		StringBuilder sb = new StringBuilder();
		HttpEntity httpEntity = response.getEntity();  
		if(httpEntity != null){
			httpEntity = new BufferedHttpEntity(httpEntity);  
		    InputStream is = httpEntity.getContent();  
		    BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
		    String str;
		    while((str=br.readLine())!=null){
		    	sb.append(str);
		    }
		    is.close();
		}
		return sb.toString();
	}


6、文件上传

 public String uploadAttachment(HttpServletRequest request){
		String json = null;
		HttpClient client = TicketUtils.getClient(); 
		try {
			
			HttpPost post = new HttpPost(url);
			
			DiskFileItemFactory fac = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(fac);
			upload.setHeaderEncoding("UTF-8");
			@SuppressWarnings("unchecked")
			List<FileItem> fileList = upload.parseRequest(request);
			Iterator<FileItem> it = fileList.iterator();
			List<File> tempFileList = new ArrayList<File>();
			while (it.hasNext()) {
				FileItem item = it.next();
				if (!item.isFormField()) {
					String fileName = item.getName();
					if (fileName != null)
				     {
				      File file = new File(fileName);
				      item.write(file);
				      MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,Charset.forName("UTF-8")); 
				      FileBody fileBody = new FileBody(file); 
				      multipartEntity.addPart(fileName, fileBody);  
				      post.setEntity(multipartEntity);
				      tempFileList.add(file);
				     }
				}	
			}
			HttpResponse response = client.execute(post);
			json = TicketUtils.getResponseBodyAsString(response);
			//delete temp files
			for(File file : tempFileList){
				file.delete();
			}
		} catch (Exception e) {
			log.error(e);
			json = JsonUtil.getJsonString(Const.ERROR_MESSAGE, EM.TICKET_EXCEPTION);
		}finally{
			client.getConnectionManager().shutdown();
		}
        return json;
    }


7、文件下载

 public void downloadAttachment(HttpServletRequest request, HttpServletResponse response, @PathVariable("fileId") Integer fileId){
		HttpClient client = TicketUtils.getClient(); 
		try {
	        HttpGet get = new HttpGet(urlStr); 
	        
	        ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() {  
                public byte[] handleResponse(HttpResponse response)  
                        throws ClientProtocolException, IOException {  
                    HttpEntity entity = response.getEntity();  
                    if (entity != null) {  
                        return EntityUtils.toByteArray(entity);  
                    } else {  
                        return null;  
                    }  
                }  
            };
            byte[] charts = client.execute(get, handler);
	        
	        URL url = new URL(urlStr);
	        HttpURLConnection uc = (HttpURLConnection)url.openConnection();
	        response.reset();
			response.addHeader("Content-disposition",uc.getHeaderField("Content-disposition"));
			OutputStream output = new BufferedOutputStream(response.getOutputStream());
	        output.write(charts); 
	        output.flush();
	        output.close();  
	        get.releaseConnection();
		} catch (Exception e) {
			log.error(e);
		}finally{
			client.getConnectionManager().shutdown();
		}
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在Java中,我们可以使用以下两种方法来发送POST请求: 1. 使用`HttpURLConnection`类 `HttpURLConnection`是Java标准库提供的一个类,用于发送HTTP请求。我们可以使用`HttpURLConnection`实现POST请求示例代码如下: ```java import java.io.*; import java.net.*; public class PostExample { public static void main(String[] args) { try { String url = "http://example.com/api"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // 设置请求方法为POST con.setRequestMethod("POST"); // 设置请求头 con.setRequestProperty("Content-Type", "application/json"); String data = "{\"name\":\"John\", \"age\":30}"; // 开启输出流,并写入请求参数 con.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream()); out.write(data); out.close(); // 读取响应 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // 打印响应结果 System.out.println(response.toString()); } catch (Exception e) { e.printStackTrace(); } } } ``` 在上面的示例中,我们首先创建了一个`HttpURLConnection`对象,并设置请求方法为POST。然后设置请求头为`Content-Type: application/json`,表示请求参数的格式为JSON字符串。接下来,我们将请求参数写入`OutputStream`中,发送POST请求。最后,读取响应结果并打印出来。 2. 使用第三方库 除了使用`HttpURLConnection`类发送POST请求外,我们也可以使用一些第三方库来简化代码,例如`Apache HttpClient`和`OkHttp`。这些第三方库提供了更加简洁易用的API,可以大大减少编码量。以`OkHttp`为例,代码如下: ```java import okhttp3.*; public class PostExample { public static void main(String[] args) { try { String url = "http://example.com/api"; OkHttpClient client = new OkHttpClient(); MediaType mediaType = MediaType.parse("application/json"); RequestBody body = RequestBody.create(mediaType, "{\"name\":\"John\", \"age\":30}"); Request request = new Request.Builder() .url(url) .post(body) .addHeader("Content-Type", "application/json") .build(); Response response = client.newCall(request).execute(); // 打印响应结果 System.out.println(response.body().string()); } catch (Exception e) { e.printStackTrace(); } } } ``` 在上面的示例中,我们使用`OkHttpClient`类创建了一个HTTP客户端,并使用`RequestBody`类创建了请求参数。然后,我们通过`Request.Builder`类构建请求对象,并设置请求方法为POST。最后,我们发送POST请求并读取响应结果。 ### 回答2: Java中的post请求方法指的是使用HTTP协议中的post方法发送请求并接收响应的方法。 在Java中,我们可以使用多种方式来实现post请求方法。 一种常用的方式是使用Java的URLConnection类来发送post请求。该类可以通过openConnection()方法创建一个URLConnection对象,然后可以设置请求方法为post,并设置请求的参数和请求头等信息,最后调用getInputStream()方法获取响应内容。 另一种方式是使用Apache HttpClient库来发送post请求。该库提供了更加简洁和易用的API来发送HTTP请求。我们可以通过创建一个HttpPost对象,设置请求的URL和请求参数等信息,然后通过HttpClient对象的execute()方法发送请求并获取响应。 除了上述两种方式外,还可以使用第三方的HTTP客户端库,如OkHttp等,来发送post请求。 在编写post请求方法时,通常需要注意以下几点: 1. 导入相关的包和类,如java.net包中的URLConnection类、org.apache.http包中的HttpPost类等; 2. 构建请求URL和请求参数等信息; 3. 设置请求方法为post,并设置请求头信息; 4. 发送请求并获取响应; 5. 处理响应结果,如解析JSON、XML等格式的响应数据。 总之,Java中可以使用多种方式来实现post请求方法,根据具体的需求和使用场景选择合适的方式。 ### 回答3: Java中的POST请求方法是一种用于向服务器提交数据的HTTP请求方式。在Java中,可以使用多种方法来发送POST请求,其中最常见的方法是使用Java的HttpURLConnection类或Apache的HttpClient库。 使用HttpURLConnection类发送POST请求的步骤如下: 1. 创建一个URL对象,指定要发送POST请求的目标URL。 2. 调用URL对象的openConnection()方法,创建一个HttpURLConnection对象。 3. 设置请求方法为POST,即conn.setRequestMethod("POST")。 4. 设置请求头部,如设置Content-Type、Accept等。 5. 创建一个输出流,将要发送的数据写入到输出流中。 6. 调用conn.getOutputStream()方法获取输出流,并将其连接到输出流。 7. 发送请求并获取服务器的响应。可以使用conn.getResponseCode()获取响应的状态码,使用conn.getInputStream()获取响应的输入流。 8. 读取服务器响应的数据,可以使用BufferedReader等类进行读取。 9. 关闭连接,释放资源。 使用Apache的HttpClient库发送POST请求的步骤如下: 1. 创建一个HttpClient对象。 2. 创建一个HttpPost对象,指定要发送POST请求的目标URL。 3. 创建一个List<NameValuePair>对象,用于存放请求的参数。 4. 向List对象中添加参数,如nameValuePairs.add(new BasicNameValuePair("param1", "value1"))。 5. 创建一个UrlEncodedFormEntity对象,将List对象编码为请求体的实体。 6. 将请求体的实体设置给HttpPost对象,即httpPost.setEntity(urlEncodedFormEntity)。 7. 执行POST请求,获取响应对象HttpResponse。 8. 读取响应对象的内容,可以使用EntityUtils等工具类进行读取。 9. 关闭连接,释放资源。 总的来说,以上就是Java中发送POST请求方法。根据不同的需求和场景,可以选择HttpURLConnection类或Apache的HttpClient库进行发送POST请求的实现。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值