java HTTP get post请求,获取二进制文件实现

public class HttpPlugin{
 private static Log log = LogFactory.getLog(HttpPlugin.class);
 @Override
 public void init() {
  
 }
 

 public void sendGet(String url , Parameter param)
 {
  StringBuffer p=new StringBuffer();
  boolean first=true;
  for(Map.Entry<String, String> pair : param.parameters.entrySet()){
   if(first) first=false;
   else p.append('&');
   p.append(pair.getKey());
   p.append('=');
   p.append(pair.getValue());
  }
  try
  {
   String urlName = url + "?" + p.toString();
   URL realUrl = new URL(urlName);
   URLConnection conn = realUrl.openConnection();

   conn.connect();
   //获取所有响应头字段
   Map<String,List<String>> map = conn.getHeaderFields();
   for (String key : map.keySet())
   {
   System.out.println(key + "--->" + map.get(key));
   }
   
   Scanner scanner=new Scanner(conn.getInputStream(),"gb2312");//以gb2312格式接收,避免中文乱码
   StringBuffer str=new StringBuffer();
   while(scanner.hasNextLine()) {
           str.append(scanner.nextLine());
           str.append("/n");
   }
   
   System.out.println(str.toString());
   
  }catch(Exception e){
   log.error(e.getMessage());
  }
 }
 

 public void sendPost(String url,Parameter param)
 {
  PrintWriter out = null;
  String result = "";
  try{
   URL realUrl = new URL(url);
   URLConnection conn = realUrl.openConnection();
   //发送POST请求设置
   conn.setDoOutput(true);
   conn.setDoInput(true);

   out = new PrintWriter(conn.getOutputStream());
   
   boolean first=true;
   for(Map.Entry<String, String> pair : param.parameters.entrySet()){
    if(first) first=false;
    else out.print('&');
    out.print(pair.getKey());
    out.print('=');
    out.print(pair.getValue());
   }
   out.flush();
   
   Scanner scanner=new Scanner(conn.getInputStream(),"gb2312");//以gb2312格式接收
   StringBuffer str=new StringBuffer();
   while(scanner.hasNextLine()) {
           str.append(scanner.nextLine());
           str.append("/n");
   }
   
   System.out.println(str.toString());
   
   if (out != null){
    out.close();
   }
  }catch(Exception e){
   log.error(e.getMessage());
  }
  System.out.println(result);
 }
 
 public boolean getBinaryFile(String url){
  try{
   URL u = new URL(url);
   URLConnection uc = u.openConnection();
   String contentType = uc.getContentType();
   int contentLength = uc.getContentLength();
 
   if (contentType.startsWith("text/") || (contentLength == -1))
   {
    log.error("getBinaryFile-->not a binary file");
    return false;
   }
 
   InputStream raw = uc.getInputStream();
   InputStream in = new BufferedInputStream(raw);
   byte[] data = new byte[contentLength];
   int bytesRead = 0;
   int offset = 0;
   while (offset < contentLength)
   {
    bytesRead = in.read(data,offset,data.length-offset);
    if(bytesRead == -1) break;
    offset +=bytesRead;
   }
   in.close();
 
   if (offset != contentLength)
   {
    log.error("getBinaryFile-->Only read "+offset+" bytes;Expected "+contentLength+" bytes.");
    return false;
   }
 
   String fileName = u.getFile();
   String filePath = "D://";
   fileName = fileName.substring(fileName.lastIndexOf('/')+1);
   FileOutputStream fout = new FileOutputStream(filePath+fileName);
   fout.write(data);
   fout.flush();
   fout.close();
  }catch(Exception e){
   log.error(e.getMessage());
   return false;
  }
  return true;
 }
 
 
 public Parameter getParameter(){
  return new Parameter();
 }
 
 
 public class Parameter{
  private Map<String,String> parameters=new HashMap<String,String>();
  private Parameter(){
   parameters=new HashMap<String,String>();
  }
  public boolean addParam(String name,String value){
   if(parameters!=null){
    parameters.put(name, value);
    return true;
   }else{
    return false;
   }
  }
  public boolean delParam(String name){
   if(parameters!=null){
    if(parameters.remove(name)==null){
     return false;
    }else{
     return true;
    }
   }else{
    return false;
   }
  }
 }

}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Netty中解析multipart/form-data请求体中的二进制数据需要进行以下步骤: 1. 创建一个自定义的ChannelHandler来处理HTTP请求。你可以扩展Netty的`SimpleChannelInboundHandler`类,并重写`channelRead0`方法。 2. 在`channelRead0`方法中,检查请求是否是multipart/form-data类型。你可以通过检查请求头的Content-Type来判断。如果是multipart/form-data类型的请求,你需要使用Netty提供的`HttpPostRequestDecoder`来解码请求体。 3. 创建一个新的`HttpPostRequestDecoder`对象,并将HTTP请求传递给它。然后,使用`isMultipart`方法检查请求是否是一个有效的multipart请求。 4. 使用`offer`方法将所有的HTTP请求内容添加到`HttpPostRequestDecoder`中,直到请求被完全解码。 5. 使用`next()`方法从解码器中获取每个解码后的HTTP内容。通常,这将返回一个`InterfaceHttpData`对象,你可以根据其类型进行处理。 6. 如果`InterfaceHttpData`是`FileUpload`类型,那么这个对象就代表一个上传的文件。你可以使用`FileUpload`对象的方法来获取文件名、保存文件等。 7. 如果`InterfaceHttpData`是`Attribute`类型,那么这个对象就代表一个表单字段。你可以使用`Attribute`对象的方法来获取字段名和字段值。 下面是一个示例代码片段,展示了如何在Netty中解析multipart/form-data请求体中的二进制数据: ```java import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.multipart.Attribute; import io.netty.handler.codec.http.multipart.FileUpload; import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder; public class MultipartHandler extends SimpleChannelInboundHandler<FullHttpRequest> { @Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { if (request.method() == HttpMethod.POST && HttpHeaders.is100ContinueExpected(request)) { ctx.writeAndFlush(ctx.alloc().buffer().writeBytes("HTTP/1.1 100 Continue\r\n\r\n".getBytes())); } if (request.method() == HttpMethod.POST && request.headers().contains(HttpHeaders.Names.CONTENT_TYPE)) { String contentType = request.headers().get(HttpHeaders.Names.CONTENT_TYPE); if (contentType.startsWith("multipart/form-data")) { HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(request); while (decoder.hasNext()) { InterfaceHttpData data = decoder.next(); if (data != null) { if (data instanceof FileUpload) { FileUpload fileUpload = (FileUpload) data; // 处理上传的文件 String fileName = fileUpload.getFilename(); // 保存文件到磁盘等操作 } else if (data instanceof Attribute) { Attribute attribute = (Attribute) data; // 处理表单字段 String fieldName = attribute.getName(); String fieldValue = attribute.getValue(); } data.release(); } } } } } } ``` 这只是一个简单的示例,你可以根据你的需要进行调整和扩展。请注意,这个示例中使用的是Netty 4.x版本的API,如果你使用的是其他版本,可能会有一些差异。确保你根据你使用的Netty版本进行相应的调整。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值