#能力开放平台系列Fiddler访问Rest服务

问题

最近开发能力开放平台,需要将Dubbo服务转换成Rest服务,虽然转换很成功(后续文档会写出如何将Dubbo服务转换成Rest接口),但是调试起来特别的麻烦。

解决方案:

Fiddler解决方案:

下载Fiddler,然后只需要添加一小段代码就能进行调试了:
如下

Java代码解决方案

然后想到用Java代码去访问。首先将下列代码添加到build.gradle中

compile 'org.apache.httpcomponents:httpclient:4.5'

代码如下:

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Map;

public class HttpClientUtil {
    private static final Log logger = LogFactory.getLog(HttpClientUtil.class);

    public static String sendPostRequest(String url, String data) throws IOException,
            URISyntaxException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(new URL(url).toURI());
        StringEntity dataEntity = new StringEntity(data, ContentType.APPLICATION_JSON);
        httpPost.setEntity(dataEntity);
        CloseableHttpResponse response = httpclient.execute(httpPost);
        try {
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        entity.getContent()));
                StringBuffer buffer = new StringBuffer();
                String tempStr;
                while ((tempStr = reader.readLine()) != null)
                    buffer.append(tempStr);
                return buffer.toString();
            } else {
                throw new RuntimeException("error code " + response.getStatusLine().getStatusCode()
                        + ":" + response.getStatusLine().getReasonPhrase());
            }
        } finally {
            response.close();
            httpclient.close();
        }
    }


    public static void main(String[] args) throws IOException, URISyntaxException {

        String result = HttpClientUtil.sendPostRequest(
                "http://10.1.50.81:20880/xxx/xxx/xxx", "{\"count\":1}");
        System.out.println("++++++++++++  " + result);

    }
}

-EOF

原文地址:https://www.cnblogs.com/yinxiangnan/p/4739044.html