您的位置:首页 > 理论基础 > 计算机网络

http post/get 2种使用方式

2015-10-27 18:05 471 查看
[code]

public class HttpUtil {

 //HttpPost
 public static String executePost(String url, List<NameValuePair> list) {
  HttpPost post = new HttpPost(url);
  // HttpDelete
  // post.addHeader("Authorization", "MDowMDExMTExMTExMTE="); // 认证token
  // post.addHeader("Content-type", "text/xml;charset=UTF-8");
  // post.addHeader("Connection", "keep-alive");
  if (list != null && list.size() > 0) {
   try {
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,
      HTTP.UTF_8);
    post.setEntity(entity);
   } catch (UnsupportedEncodingException e) {
    e.printStackTrace();
   }
  }
  HttpClient client = new DefaultHttpClient();
  try {
   HttpResponse response = client.execute(post);

//   response.getHeaders("Authorization");   ????????????????????token?

   if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
    String result = EntityUtils.toString(response.getEntity());
    return result;
   } else {
    return "-2";
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  return "-2";
 }

 //HttpGet
 public static String executeGet(String url, Map<String, String> params, String encoding) throws Exception {

  // 使用StringBuilder对象
  StringBuilder sb = new StringBuilder(url);
  sb.append('?');

  // 迭代Map
  for (Map.Entry<String, String> entry : params.entrySet()) {
   sb.append(entry.getKey()).append('=').append(
     URLEncoder.encode(entry.getValue(), encoding)).append('&');
  }
  sb.deleteCharAt(sb.length() - 1);
  // 打开链接
  URL url2 = new URL(sb.toString());
  HttpGet get = new HttpGet(url2);
  // HttpDelete
  // get .addHeader("Authorization", "MDowMDExMTExMTExMTE="); // 认证token
  // get .addHeader("Content-type", "text/xml;charset=UTF-8");
  // get .addHeader("Connection", "keep-alive");

  // HttpParams params = new BasicHttpParams();
  // ConnManagerParams.setTimeout(params, 20000);
  // get.setParams(params);
  HttpClient client = new DefaultHttpClient();
  try {
   HttpResponse response = client.execute(get);
   if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
    String result = EntityUtils.toString(response.getEntity());
    return result;
   } else {
    return "-2";
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  return "-2";
 }

HttpURLConnection 方式:
=====================

 //HttpURLConnection  get

  public void sendSms() throws Exception{
        String message="货已发到";
        message=URLEncoder.encode(message, "UTF-8");
        System.out.println(message);
        String path ="http://localhost:8083/DS_Trade/mobile/sim!add.do?message="+message;
        URL url =new URL(path);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setConnectTimeout(5*1000);
        conn.setRequestMethod("GET");
        InputStream inStream = conn.getInputStream();    
        byte[] data = StreamTool.readInputStream(inStream);
        String result=new String(data, "UTF-8");
        System.out.println(result);
    }

 HttpURLConnection方式:

 //HttpURLConnection  post

 public static String uploads(String xml, String path, String authorization) {
  try {
   byte[] data = xml.getBytes("UTF-8");
   URL url = new URL(path);
   HttpURLConnection conn = (HttpURLConnection) url.openConnection();
   conn.setConnectTimeout(8 * 1000);
   conn.setReadTimeout(8 * 1000);
   conn.setDoInput(true);// 允许输入
   conn.setDoOutput(true);// 允许输出
   conn.setUseCaches(false);
   conn.setRequestMethod("POST"); // Post方式
   conn.setRequestProperty("connection", "keep-alive"); // 客户端到服务器端的连接持续有效
   conn.setRequestProperty("Authorization", authorization);
   conn.setRequestProperty("Content-Type",
     "application/json; charset=UTF-8");
   conn.setRequestProperty("Content-Length",
     String.valueOf(data.length));

   OutputStream outStream = conn.getOutputStream();
   outStream.write(data);
   outStream.flush();
   outStream.close();
   StringBuffer buf = new StringBuffer();
   String s = "";

   if (conn.getResponseCode() == 200) {
    InputStream in = conn.getInputStream();
    BufferedReader br = new BufferedReader(
      new InputStreamReader(in));
    while ((s = br.readLine()) != null) {
     buf.append(s);
    }
    br.close();
    in.close();
   }
   return buf.toString();
  } catch (Exception e) {
   e.printStackTrace();
  }
  return "-2";
 }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: