zoukankan      html  css  js  c++  java
  • httpclient get/post请求

    public static String httpPost(String url, JSONObject json) {
    String respContent = null;
    try{
    HttpPost httpPost = new HttpPost(url);
    CloseableHttpClient client = HttpClients.createDefault();

    // json方式
    StringEntity entity = new StringEntity(json.toString(), "utf-8");// 解决中文乱码问题
    entity.setContentEncoding("UTF-8");
    entity.setContentType("application/json");
    httpPost.setEntity(entity);
    System.out.println();
    HttpResponse resp = client.execute(httpPost);
    if (resp.getStatusLine().getStatusCode() == 200) {
    HttpEntity he = resp.getEntity();
    respContent = EntityUtils.toString(he, "UTF-8");
    }
    }catch (Exception ex) {
    // TODO: handle exception
    respContent=null;
    }finally {
    return respContent;
    }
    }

    /**
    * @param url
    * 要请求的地址
    * @return 状态码
    * @throws IOException
    * @throws ClientProtocolException
    */
    public static String httpGet(String url) {
    String urlNameString = url;
    String status = null;
    try {
    // 根据地址获取请求
    HttpGet request = new HttpGet(urlNameString);// 这里发送get请求
    request.getParams().setParameter(HttpMethodParams.SO_TIMEOUT,3000 );
    // 获取当前客户端对象
    HttpClient httpClient = new DefaultHttpClient();
    // 通过请求对象获取响应对象
    HttpResponse response;
    response = httpClient.execute(request);
    // 判断网络连接状态码是否正常(0--200都数正常)
    if (response.getStatusLine().getStatusCode() == 200) {
    status = "200";
    }
    }
    catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    log.error(e);
    }
    finally {
    return status;
    }
    }

  • 相关阅读:
    Java中的访问修饰符详细解析
    Java继承 练习题
    (转)Java 内存整理——堆、栈、常量池
    关于Char思考题
    如何使用帮助文档
    工具类的来由与静态方法
    题解 【NOIP2011】计算系数
    题解 【Uva】硬币问题
    题解 【NOIP2006】作业调度方案
    题解 【NOIP2003】神经网络
  • 原文地址:https://www.cnblogs.com/coderdxj/p/7808628.html
Copyright © 2011-2022 走看看