初用Httpclient笔记

本文介绍了一种使用Java实现HTTP客户端请求的方法,包括GET和POST请求的处理方式,展示了如何设置请求头来模拟浏览器行为,以及如何处理不同类型的请求数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    

        // 伪装浏览器请求

private static String userAgent = "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36";

private static String contentType = "application/json;charset=utf-8";

private static String accept = "application/json";

        public static String getHttpClient(String url, String query) {
// 创建client和post对象

HttpClient client = HttpClients.createDefault();

                //post请求用于(key-value)类型

HttpPost post = new HttpPost(url);
post.setHeader("User-Agent", userAgent); // 伪装浏览器请求
// json形式
post.addHeader("content-type", contentType);
post.addHeader("accept", accept);
post.setEntity(new StringEntity(query, Charset.forName("utf-8"))); // json字符串以实体的实行放到post中
HttpResponse response = null;
try {
response = client.execute(post); // 获得response对象
} catch (Exception e) {
e.printStackTrace();
}
String result = "";
if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode()) {
result = "请求返回不正确";
return result;
}
try {
result = EntityUtils.toString(response.getEntity()); // 获得字符串形式的结果
} catch (Exception e) {
e.printStackTrace();
}
return result;

}

        

        //创建传入NameValuePair集合类型的参数

        //NameValuePair键值对类型的实体  个人比较推荐使用 第一种String类型 比较灵活 自由选择

        public static JSONObject getHttpClient(String url,List<? extends NameValuePair> formparams) {
JSONObject dataJson = new JSONObject();
// 创建默认的httpClient实例.
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建httppost
HttpPost httppost = new HttpPost(url);
UrlEncodedFormEntity uefEntity;

CloseableHttpResponse response = null;
try {
uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
httppost.setEntity(uefEntity); 
System.out.println("executing request " + httppost.getURI());
response = httpclient.execute(httppost);
}catch (Exception e) {
e.printStackTrace();
}

if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode()) {
dataJson.put("errMsg", "错误码"+response.getStatusLine().getStatusCode());
}

try {
HttpEntity entity = response.getEntity();
if (entity != null) {
String str = EntityUtils.toString(entity, "UTF-8");
System.out.println("Response content: "+ str);
System.out.println(str);
JSONObject queryJson = JSON.parseObject(str);
dataJson.put("errMsg", queryJson.getString("errMsg"));
dataJson.put("success", queryJson.getString("success"));
}
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}

return dataJson;
}

        


        //创建get类

        public static String doGet(String url) {  
            try {  
                HttpClient client = new DefaultHttpClient();  
                //发送get请求  
                HttpGet request = new HttpGet(url);  
                HttpResponse response = client.execute(request);  
   
                /**请求发送成功,并得到响应**/  
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {  
                /**读取服务器返回过来的json字符串数据**/  
                String strResult = EntityUtils.toString(response.getEntity());  
                  
                return strResult;  
            }  
        } catch (IOException e) {  
                e.printStackTrace();  
        } 
        return null;  
    }


        


    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值