中转api,一个用于转发用户的Http请求的工具

有时候由于限制或者其他原因,不能直接访问外部的接口,我们就需要一个中转站,用于中转用户的请求,将用户的请求发送到目的地址,然后返回用户需要的结果。

众所周知,Http请求分请求头和请求体,响应也分响应头和响应体。所以我们中转的时候一般需要设置请求头、请求体,但是响应只需要返回响应体即可。我们可以使用json来描述我们的参数和响应。

 

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.AllClientPNames;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 参数 { "requestUrl": "http://10.95.253.74:17001/bp220.go?method=init",
 * "requestData": "{}", "requestMode": "POST", "contentType":
 * "application/json;charset=UTF-8", "inputCharset": "UTF-8", "outputCharset":
 * "UTF-8", "clientOutputCharset": "UTF-8",
 * headers:[{"headerName":"Content-Type","headerValue":"application/json"},{
 * "headerName":"Accept","headerValue":"gzip"}] }
 * 
 * 
 * 返回值 { "ResultCode":200, "ResultMsg":"SUCCESS", "Data":"{"key","value"}"
 * 
 * }
 */

@Path("/rest/transfer")
public class TransferApiResource{
    private static final Logger logger              = LoggerFactory.getLogger(TransferApiResource.class);
    private static final String requestData         = "";
    private static final String requestMode         = "POST";
    private static final String contentType         = "application/json";
    private static final String xinputCharset       = "UTF-8";
    private static final String xoutputCharset      = "UTF-8";
    private static final String clientOutputCharset = "UTF-8";

    @POST
    @Path("/send")
    @Consumes({ MediaType.APPLICATION_JSON })
    @Produces(MediaType.APPLICATION_JSON)
    public String send(String body){
        JSONObject bodyAsJson = new JSONObject(body);
        // 初始化参数
        String url = bodyAsJson.getString("requestUrl");
        String data = (bodyAsJson.has("requestData")) ? bodyAsJson.getString("requestData") : requestData;
        String inputCharset = (bodyAsJson.has("inputCharset")) ? bodyAsJson.getString("inputCharset") : xinputCharset;
        String outputCharset = (bodyAsJson.has("outputCharset")) ? bodyAsJson.getString("outputCharset")
                : xoutputCharset;
        String clientOutput = (bodyAsJson.has("clientOutputCharset")) ? bodyAsJson.getString("clientOutputCharset")
                : clientOutputCharset;
        String mode = (bodyAsJson.has("requestMode")) ? bodyAsJson.getString("requestMode") : requestMode;
        String type = (bodyAsJson.has("contentType")) ? bodyAsJson.getString("contentType") : contentType;

        JSONArray headArray = new JSONArray();
        if(bodyAsJson.has("headers")){
            headArray = bodyAsJson.getJSONArray("headers");
        }
        Map<String, String> headers = jsonArray2Map(headArray);

        String result = getReturn(url, data, inputCharset, outputCharset, clientOutput, mode, type, headers);
        return result;
    }

    /**
     * @Title: jsonArray2Map
     * @Description:jsonarray转换成map
     * @param headArray
     * @return Map<String,String>
     */

    private Map<String, String> jsonArray2Map(JSONArray headArray){
        Map<String, String> map = new HashMap<String, String>();
        int len = headArray.length();
        for(int i = 0; i < len; i++){
            JSONObject object = headArray.getJSONObject(i);
            map.put(object.getString("headerName"), object.getString("headerValue"));
        }
        return map;
    }

    @SuppressWarnings({ "deprecation", "resource" })
    public static String getReturn(String restUrl, String requestData, String inputCharset, String outputCharset,
            String clientOutputCharset, String requestMode, String contentType, Map<String, String> headers){
        HttpClient httpClient = new DefaultHttpClient();
        httpClient.getParams().setParameter(AllClientPNames.CONNECTION_TIMEOUT, 30000);
        httpClient.getParams().setParameter(AllClientPNames.SO_TIMEOUT, 30000);
        // httpClient.getParams().setParameter("http.protocol.version",
        // HttpVersion.HTTP_1_1);
        httpClient.getParams().setParameter("http.protocol.content-charset", inputCharset);
        HttpGet httpGet = null;
        HttpPost httpPost = null;
        JSONObject result = new JSONObject();
        HttpEntity entity = null;
        HttpResponse response = null;
        try{
            if(TransferApiResource.requestMode.equalsIgnoreCase(requestMode)){
                // POST请求
                httpPost = new HttpPost(restUrl);
                StringEntity reqEntity = new StringEntity(requestData, inputCharset);
                reqEntity.setContentType(contentType);
                reqEntity.setContentEncoding(inputCharset);
                httpPost.setEntity(reqEntity);
                // httpPost.setHeader("Accept", MediaType.APPLICATION_JSON);

                // 设置header
                for(Map.Entry<String, String> entry : headers.entrySet()){
                    httpPost.addHeader(entry.getKey(), entry.getValue());
                }

                response = httpClient.execute(httpPost);

            } else{
                httpGet = new HttpGet(restUrl);
                // httpGet.setHeader("Accept", MediaType.APPLICATION_JSON);

                // 设置header
                for(Map.Entry<String, String> entry : headers.entrySet()){
                    httpGet.addHeader(entry.getKey(), entry.getValue());
                }

                response = httpClient.execute(httpGet);
            }

            int status = response.getStatusLine().getStatusCode();
            logger.info("网络状态:status=" + status);
            if(HttpStatus.SC_OK == status){
                entity = response.getEntity();
                String ret = "";
                if(entity != null){
                    ret = new String(EntityUtils.toString(entity).getBytes(outputCharset), clientOutputCharset);
                }

                result.put("ResultCode", HttpStatus.SC_OK);
                result.put("ResultMsg", "SUCCESS");
                result.put("Data", ret);

            } else{
                entity = response.getEntity();
                String error = new String(EntityUtils.toString(entity).getBytes(outputCharset), clientOutputCharset);
                String ret = "网络错误:错误代码" + status + "," + error;

                result.put("ResultCode", status);
                result.put("ResultMsg", "FAIL");
                result.put("Data", ret);
            }
            return result.toString();
        }
        catch(Exception e){
            e.printStackTrace();
            result.put("ResultCode", 500);
            result.put("ResultMsg", "EXCEPTION");
            return result.toString();
        }
        finally{
            if(null != entity){
                try{
                    EntityUtils.consume(entity);
                }
                catch(IOException e){
                    e.printStackTrace();
                }
            }
            if(null != httpGet && httpGet.isAborted()){
                httpGet.abort();
            }
            if(null != httpPost && httpPost.isAborted()){
                httpPost.abort();
            }
            if(null != httpClient){
                httpClient.getConnectionManager().shutdown();
            }
        }

    }
}

 

 

 

 

 

  • 0
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
可以通过以下步骤在 C# 中使用 Web API 中转上传文件到文件服务器: 1. 创建一个 Web API 控制器来处理上传请求,例如: ```csharp public class FileUploadController : ApiController { [HttpPost] public async Task<IHttpActionResult> Upload() { // 处理上传请求 // ... } } ``` 2. 在上传请求中,使用 `MultipartFormDataStreamProvider` 类来处理上传的文件和表单数据。例如: ```csharp public async Task<IHttpActionResult> Upload() { // 验证上传请求是否为 multipart/form-data if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } // 设置文件上传目录 var uploadPath = HttpContext.Current.Server.MapPath("~/Uploads"); // 处理上传的文件和表单数据 var provider = new MultipartFormDataStreamProvider(uploadPath); await Request.Content.ReadAsMultipartAsync(provider); // 获取上传的文件 var file = provider.FileData.FirstOrDefault(); // 将文件上传到文件服务器 // ... } ``` 3. 使用 `WebClient` 类或其他 HTTP 客户端库将文件上传到文件服务器。例如: ```csharp public async Task<IHttpActionResult> Upload() { // ... // 将文件上传到文件服务器 var fileStream = File.OpenRead(file.LocalFileName); var client = new WebClient(); client.UploadFile("http://fileserver/upload", fileStream); // 删除上传的临时文件 File.Delete(file.LocalFileName); return Ok(); } ``` 4. 在文件服务器上处理上传的文件。例如,在 ASP.NET Core 中,可以使用 `IFormFile` 类来处理上传的文件。例如: ```csharp [HttpPost("upload")] public async Task<IActionResult> Upload(IFormFile file) { if (file == null || file.Length == 0) { return BadRequest(); } // 保存上传的文件 var filePath = Path.Combine(_hostingEnvironment.ContentRootPath, "uploads", file.FileName); using (var stream = new FileStream(filePath, FileMode.Create)) { await file.CopyToAsync(stream); } return Ok(); } ``` 以上是一个基本的上传文件的流程,具体的实现细节可以根据具体的需求进行调整。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值