一个简单的httpclient post调用实例

 

public static String posts(String url, String json) {
		System.out.println(json);
        HttpPost httppost = new HttpPost(url);
        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            List parameters4 = new ArrayList();
            parameters4.add(new BasicNameValuePair("data", json));
            HttpEntity entms4 = new UrlEncodedFormEntity(parameters4, "UTF-8");
            httppost.setEntity(entms4);
            CloseableHttpResponse response = httpclient.execute(httppost);
            HttpEntity entity4 = response.getEntity();
            if (entity4 != null) {
                String res = EntityUtils.toString(entity4, "utf-8");
                return res;
            }
            httppost.abort();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

 

你可能感兴趣的:(Java)