Call third-party interfaces get in the way data java

// get request method

private String getInfo(Map<String, Object> params,String URL) {

// Create Httpclient objects
CloseableHttpClient = HttpClients.createDefault HttpClient ();
CloseableHttpResponse the Response = null;
String ResultString = null;
the try {
// Create uri
UriBuilder Builder = new new UriBuilder (the URL of);
IF (! Params = null) {
for (String Key: params.keySet ()) {
builder.addParameter (Key, params.get (Key) .toString ());
}
}
the URI URI = builder.build ();
// Create http GET request
HttpGet httpGet = new HttpGet ( URI);
// execution request
response = httpclient.execute (httpGet);
whether the returned status is determined // 200 is
iF (response.getStatusLine () getStatusCode () == 200 is) {.
ResultString = EntityUtils.toString (response.getEntity ( ), "UTF-8") ;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}

 

// post request method

private String getInfo(Map<String, Object> params, String URL) {
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(URL);
if (params != null) {
for (String key : params.keySet()) {
builder.addParameter(key, params.get(key).toString());
}
}
URI uri = builder.build();
// 创建http POST请求
HttpPost httpPost = new HttpPost(uri);

// 执行请求
response = httpclient.execute(httpPost);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(),"UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}

 

// transmit type parameter json post request
Private getCarMapInfo String (String json, the URL String) {
// create objects Httpclient
CloseableHttpClient httpClient HttpClients.createDefault = ();
CloseableHttpResponse Response = null;
String ResultString = null;
the try {
// Create Http Post request
HttpPost HttpPost = new new HttpPost (the URL of);
// create the requested content
StringEntity the Entity = new new StringEntity (json, ContentType.APPLICATION_JSON);
httpPost.setEntity (the Entity);

// http execution request
response = httpClient.execute (httpPost);
= EntityUtils.toString ResultString (response.getEntity (), "UTF-. 8");
} the catch (Exception E) {
e.printStackTrace ();
} {the finally
the try {
response.close ();
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}

Guess you like

Origin www.cnblogs.com/drawStart/p/12531703.html