首页 > 代码库 > HttpClient 教程

HttpClient 教程

1. 使用HttpClient

public static String methodGet(String reqUrl) {
  String result = "";
  HttpClient httpClient = new DefaultHttpClient();
  HttpGet httpGet = new HttpGet(reqUrl);
  httpGet.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
  try {
    HttpResponse httpResponse = httpClient.execute(httpGet);
    if (httpResponse.getStatusLine().getStatusCode() == 200) {
      HttpEntity entity = httpResponse.getEntity();
      result = EntityUtils.toString(entity, HTTP.UTF_8);// 返回的结果集
    }
  } catch (ClientProtocolException e) {
    e.printStackTrace();
  } catch (IOException e) {
    e.printStackTrace();
  }
  return result;
}

public static String methodPost(){
  String result = "";
  String url = "";
  HttpClient httpClient = new DefaultHttpClient();
  HttpPost httpPost = new HttpPost(url);
  List<NameValuePair> params = new ArrayList<NameValuePair>();
  params.add(new BasicNameValuePair("cp_id", "")); //传递的参数,类似map

  try {
    httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
    HttpResponse httpResponse = httpClient.execute(httpPost);
    if (httpResponse.getStatusLine().getStatusCode() == 200) {
      HttpEntity entity = httpResponse.getEntity();
      result = EntityUtils.toString(entity, HTTP.UTF_8); // 返回的json
      System.out.println(result);
    }
  } catch (Exception e) {
  }
  return result;
}

 

2.基础版本

 

public static String invidePost(String data){
  PrintWriter out=null;
  BufferedReader in =null;
  String result = "";
  try {
    URL realUrl=new URL("http://yrt.51haoyitou.com/api/spreadUserData?startday=2016-09-05&endday=2016-            09- 05&sign=9c7c03693dedf82587a43b05ac892ca3&type=38");
    URLConnection conn=realUrl.openConnection();

    // 设置通用的请求属性
    conn.setRequestProperty("accept", "*/*");
    conn.setRequestProperty("connection", "Keep-Alive");
    conn.setRequestProperty("user-agent",
    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
    // 发送POST请求必须设置如下两行
    conn.setDoOutput(true);
    conn.setDoInput(true);

    out = new PrintWriter(conn.getOutputStream());

    // 发送请求参数
    //out.print("dt={\"p1\":\"094\",\"p2\":\"admin\",\"p3\":\"10050\",\"p4\":\"192.168.1.1\"}");
    //out.print("dt="+data);
    // flush输出流的缓冲
    out.flush();
    // 定义BufferedReader输入流来读取URL的响应
    in = new BufferedReader(
    new InputStreamReader(conn.getInputStream(),"utf-8"));
    String line;
    while ((line = in.readLine()) != null) {
      result += line;
    }

    System.out.println(result);
  } catch (MalformedURLException e) {
    e.printStackTrace();
  } catch (IOException e) {
    e.printStackTrace();
  }
  finally{
    try{
      if(out!=null){
        out.close();
      }
      if(in!=null){
        in.close();
      }
    }
    catch(IOException ex){
      ex.printStackTrace();
    }
  }
  return result;
}

 

HttpClient 教程