简单代码如下:
1.Map<String, String> params = new HashMap<String, String>();
params.put("id", "11223");
params.put("nonce_str", RandomStringUtils.randomNumeric(16));
params.put("message", "...aaaabc");
DefaultHttpClient httpclient = new DefaultHttpClient();
// HttpPost post = postForm(url, params);
HttpPost httpost = new HttpPost(url);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
Set<String> keySet = params.keySet();
for (String key : keySet) {
nvps.add(new BasicNameValuePair(key, params.get(key)));
}
try {
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
HttpResponse response = httpclient.execute(httpost);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
//释放链接
httpclient.getConnectionManager().shutdown();
2.HttpClient httpClient= new DefaultHttpClient();
HttpPost post = new HttpPost(DETECT_URL);
HttpEntity resEntity = null ;
try {
MultipartEntity mutiEntity = new MultipartEntity();
mutiEntity.addPart("api_key", new StringBody("a", Charset.forName("UTF-8")));
mutiEntity.addPart("api_secret", new StringBody("b", Charset.forName("UTF-8")));
mutiEntity.addPart("image_file" , new FileBody(image_file));
post.setEntity(mutiEntity);
HttpResponse response = httpClient.execute(post);
resEntity = response.getEntity();
if (resEntity != null) {
String result = EntityUtils.toString(resEntity,"UTF-8");
return JSONObject.fromObject(result);
}
} catch(Exception e) {
log.error("f出现异常 : "+e.getMessage() , e);
throw new Exception(e.getMessage() , e);
}finally{
//释放链接
httpClient.getConnectionManager().shutdown();
}
return json ;