httpclient post

public static JSONObject doRefresh(JSONObject json)
	{
		//http 4.5
		CloseableHttpClient client = SSLClient.createSSLClientDefault();
		JSONObject response = null;
		HttpPost post = new HttpPost(URL);	    
		StringBody username = new StringBody(USERNAME, ContentType.create(
				"text/plain", Consts.UTF_8));
		StringBody password = new StringBody(PASSWORD, ContentType.create(
				"text/plain", Consts.UTF_8));
		StringBody task = new StringBody(json.toString(), ContentType.create(
				"text/plain", Consts.UTF_8));
		try
		{
			HttpEntity reqEntity = MultipartEntityBuilder.create()
					.addPart("username", username)
					.addPart("password", password).addPart("task", task)
					.build();
			post.setEntity(reqEntity);
			CloseableHttpResponse res = client.execute(post);
			if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
			{
				HttpEntity entity = res.getEntity();
				String result = EntityUtils.toString(res.getEntity());// 返回json格式
				response = JSONObject.fromObject(result);
				EntityUtils.consume(entity);
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
				if(client != null)
					client.close();
			}
			catch(IOException e)
			{
				e.printStackTrace();
			}
		}
		return response;
	}

你可能感兴趣的:(http,post,json)