首页 > 技术文章 > 获取服务端数据 Post

god-monk 2017-12-29 16:54 原文

1,urlencoder发送数据

NameValuePair pair = new NameValuePair("cnname",appliName);

PostMethod postMethod = new PostMethod(url) ;
postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8") ;
//参数设置,需要注意的就是里边不能传NULL,要传空字符串
NameValuePair[] data = {pair};
postMethod.setRequestBody(data);
HttpClient httpClient = new HttpClient();
int i = httpClient.executeMethod(postMethod);// 执行POST方法
if(200 == i){
String responseBodyAsString = postMethod.getResponseBodyAsString();
JSONObject obj = (JSONObject) JSON.parse(responseBodyAsString);
}

2.body

HttpClient httpclient = new HttpClient();
PostMethod postMethod = new PostMethod(findClaimUnderwriteDataUrl);
RequestEntity se = new StringRequestEntity(JSONObject.toJSONString(请求体), "application/json", "UTF-8");
postMethod.setRequestEntity(se);
httpclient.executeMethod(postMethod);
String resp = postMethod.getResponseBodyAsString();

3.RestTemplate

<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
</dependency>

SpringBoot启动类添加:

@Bean
public RestTemplate restTemplate(){
return new RestTemplate(new OKHttp3ClientHttpRequestFactory());
}

ResponseEntity<Map> entity = restTemplate.getForEntity(url,Map.class);
Map map = entity.getBody();

4.servlet

@SuppressWarnings("serial")
public class Customer1 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");

        resp.getWriter().print(
            "{\"response\": {\"id\": \"xxxxxxxx\"}}");
           
        resp.getWriter().close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    doGet(req, resp);
    }
}

推荐阅读