pom文件
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient-cache</artifactId>
<version>4.5</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.3.2</version>
</dependency>
一、使用get方式调用(返回json)
protected void service(HttpServletRequest request, HttpServletResponse response){
response.setCharacterEncoding("utf-8");
response.setContentType("application/json; charset=utf-8");
String urlStr= "第三方url接口";
String jsonString = null;
try {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
String line = "";
StringBuffer buffer = new StringBuffer();
while ((line = reader.readLine() )!= null){
buffer.append(line);
}
reader.close();
conn.disconnect();
jsonString = buffer.toString();
} catch (Exception e) {
e.printStackTrace();
}
PrintWriter printWriter = null;
try {
printWriter = response.getWriter();
} catch (IOException e) {
e.printStackTrace();
}
printWriter.print(jsonString );
}
二、使用post方式调用
//以后更新
三、第三方返回的是一个xml文件(get方式)
protected void service(HttpServletRequest request, HttpServletResponse response){
response.setCharacterEncoding("utf-8");
String urlStr = "第三方url接口";
String result = getInfoByHttp(urlStr);
PrintWriter printWriter = null;
try {
printWriter = response.getWriter();
} catch (IOException e) {
e.printStackTrace();
}
printWriter.print(result);
}
public static String getInfoByHttp(String url) {
HttpGet httpGet = new HttpGet(url);
HttpClient httpClient = new DefaultHttpClient();
String result = "";
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
result = getJsonStringFromGZIP(httpResponse);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static String getJsonStringFromGZIP(HttpResponse response) {
String jsonString = null;
try {
InputStream is = response.getEntity().getContent();
BufferedInputStream bis = new BufferedInputStream(is);
bis.mark(2);
// 取前两个字节
byte[] header = new byte[2];
int result = bis.read(header);
// reset输入流到开始位置
bis.reset();
// 判断是否是GZIP格式
int headerData = getShort(header);
if (result != -1 && headerData == 0x1f8b) {
is = new GZIPInputStream(bis);
} else {
is = bis;
}
InputStreamReader reader = new InputStreamReader(is, "utf-8");
char[] data = new char[100];
int readSize;
StringBuffer sb = new StringBuffer();
while ((readSize = reader.read(data)) > 0) {
sb.append(data, 0, readSize);
}
jsonString = sb.toString();
bis.close();
reader.close();
} catch (Exception e) {
}
return jsonString;
}
private static int getShort(byte[] data) {
return (int) ((data[0] << 8) | data[1] & 0xFF);
}