HTTP POST方式提交JSON数据

方式一:

	public static String postJSon(String url, String strJson)
	{
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(url);
		String result = null;
		try {
			StringEntity s = new StringEntity(strJson,"UTF-8");
//			s.setContentEncoding("UTF-8");
			s.setContentType("application/json;charset=utf-8");
			post.setEntity(s);
			HttpResponse res = client.execute(post);

			System.out.println(res.getStatusLine().getStatusCode());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return result;
	}

 方法二:

 HttpClient httpClient = new HttpClient();
	    PostMethod httpPost = new PostMethod(url);
	    
	    JSONObject data = new JSONObject();
	    data.put("username", "发达省份");
	    data.put("password", "133");
	    data.put("phonenum", "131313");
	    StringRequestEntity requestEntity = new StringRequestEntity(
	    		data.toJSONString(),
	    	    "application/json",
	    	    "UTF-8");
	    httpPost.setRequestEntity(requestEntity);
	    httpClient.executeMethod(httpPost);
	    int statusCode = httpPost.getStatusCode();
	    System.out.println("statusCode:"+statusCode);

 

你可能感兴趣的:(Java)