在后台进行使用post调用接口并传递json参数


所用到的jar包

在后台进行使用post调用接口并传递json参数_第1张图片
核心代码:

public class InterfaceTest{
	public static void main(String[] args) {
		try {
			System.out.println(getMessage());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static String getMessage()throws Exception{
        JSONObject template = new JSONObject();
        template.put("Name", "张三");
        template.put("Pass","123456");
        String urlString = "http://www.aiday.com.cn:10502/api/User/Login";
        CloseableHttpClient  httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(urlString);
        httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
        StringEntity entity;
        entity = new StringEntity(template.toString());
        System.out.println(template.toString());
        httpPost.setEntity(entity);
        HttpResponse response;
        response = httpClient.execute(httpPost);
        /*InputStream inputStream = response.getEntity().getContent();
        String name1 = name+".png";     //图片的名称
*/        
      //获取返回
      	HttpEntity entitys = response.getEntity();
      	BufferedReader in = new BufferedReader(new InputStreamReader(entitys.getContent(), "UTF-8"));
    	StringBuffer buffer = new StringBuffer();
      	String line = null;
      	while ((line = in.readLine()) != null) {
      	  buffer.append(line);
      	}
      	return buffer.toString();
    }	
}

你可能感兴趣的:(互联网)