| | |
| | | import org.apache.http.client.HttpClient; |
| | | import org.apache.http.client.methods.HttpGet; |
| | | import org.apache.http.client.methods.HttpPost; |
| | | import org.apache.http.client.methods.HttpUriRequest; |
| | | import org.apache.http.entity.StringEntity; |
| | | import org.apache.http.impl.client.DefaultHttpClient; |
| | | import org.apache.http.impl.client.HttpClients; |
| | | import org.apache.http.message.BasicHeader; |
| | | import org.apache.http.util.EntityUtils; |
| | | import org.springframework.util.ObjectUtils; |
| | | |
| | | import java.io.BufferedReader; |
| | | import java.io.IOException; |
| | | import java.io.InputStreamReader; |
| | | import java.io.OutputStreamWriter; |
| | | import java.io.*; |
| | | import java.net.MalformedURLException; |
| | | import java.net.URL; |
| | | import java.net.URLConnection; |
| | |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * get请求 |
| | | * @param url 请求地址(get请求时参数自己组装到url上) |
| | | * @param headerMap 请求头 |
| | | * @return 响应文本 |
| | | */ |
| | | public static String get(String url, Map<String, String> headerMap) { |
| | | // 请求地址,以及参数设置 |
| | | HttpGet get = new HttpGet(url); |
| | | if (headerMap != null) { |
| | | for (Map.Entry<String, String> entry : headerMap.entrySet()) { |
| | | get.setHeader(entry.getKey(), entry.getValue()); |
| | | } |
| | | } |
| | | // 执行请求,获取相应 |
| | | return getRespString(get); |
| | | } |
| | | |
| | | /** |
| | | * 获取响应信息(String) |
| | | */ |
| | | public static String getRespString(HttpUriRequest request) { |
| | | // 获取响应流 |
| | | InputStream in = getRespInputStream(request); |
| | | |
| | | StringBuilder sb = new StringBuilder(); |
| | | String line; |
| | | |
| | | BufferedReader br = new BufferedReader(new InputStreamReader(in)); |
| | | try { |
| | | while ((line = br.readLine()) != null) { |
| | | sb.append(line); |
| | | } |
| | | } catch (IOException e) { |
| | | e.printStackTrace(); |
| | | } |
| | | String str = sb.toString(); |
| | | return str; |
| | | } |
| | | |
| | | /** |
| | | * 获取响应信息(InputStream) |
| | | */ |
| | | public static InputStream getRespInputStream(HttpUriRequest request) { |
| | | // 获取响应对象 |
| | | HttpResponse response = null; |
| | | try { |
| | | response = HttpClients.createDefault().execute(request); |
| | | } catch (Exception e) { |
| | | e.printStackTrace(); |
| | | } |
| | | if (response == null) { |
| | | return null; |
| | | } |
| | | // 获取Entity对象 |
| | | HttpEntity entity = response.getEntity(); |
| | | // 获取响应信息流 |
| | | InputStream in = null; |
| | | if (entity != null) { |
| | | try { |
| | | in = entity.getContent(); |
| | | } catch (Exception e) { |
| | | e.printStackTrace(); |
| | | } |
| | | } |
| | | return in; |
| | | } |
| | | |
| | | } |