为啥HttpClient请求返回400,URL请求返回302正常

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了为啥HttpClient请求返回400,URL请求返回302正常相关的知识,希望对你有一定的参考价值。

GET方式提交的数据超长了,不要用GET方式。换成POST方式提交。
把URL的参数提取出来,不要写到URL里面。

是不是如楼上说的,长度超限制了。Get方式长度限制为1024个字节。
我在用android开发时也碰到过相似情况,通过HttpURLConnection获取网页内容时,发出请求一直返回400 。后来查下来是服务端跳转了,设置setInstanceFollowRedirects为false就行。不清楚你是不是类似的原因。

public static void main(String[] args)
try
String s = "http://mobads.baidu.com/ad.html?url=http%3A%2F%2Fm.baidu.com%2Fcpro.php%3Fa0fK000cFDtp14ipxciFcucWgFoHy2H9iL-QuuIcNAkYIMRiaPQiWnmR6W2aNPD15t3bHYIBjLSFbvjfpThNBsKZLbZAU51-HXSkBpuqvKBXOMaqOkbYINsLI1jq.Db_ipx2roRhF596OlZextW6H7sEyFBOg_vTyyxZ-9k1QjPakblN0.IgF_5y9YIZ0lQzqLILT8mh7GuZR8mvqVQsKYUHYs0Zwd5H00IvsqP6KWUMw85yFhrj61myDLgvPsT6KYI1Yz0A7bmvk9TLnqn0KzT1Ys0APYUHdBmy-bIRPdTLw2Tvq80A49IZRqr0KGIA-b5HD10A-Ypy4hUv-b5H00uLKGujYs0ZF-uMKGujYs0APsThqGujY0mMNbuvNYgvN3TA-b5H00my-s5HNGU17hPWPNmvP80ZNGTjd9pAPEPAkRn-Pzu6KWpjY0IA7z5Hc0uZws5HD0TvN_UANzgv-b5Hc0pgPxmgKs5HD0mgKsgv-b5HnznHn1P1mkPWT0mLN1IjdlpZN9UyqB0A4-I7qYXgK-5HD0Uhqs5Hfvnj0s0A7bmhkEmvVxpvN45H00pgPxIv-zuyk-TLnqnfKLmgKxIZ-suHYs0AdEmh-_uNqsUA7YuhqzUHYz0AdETdqvugcqnB31QW00TAsqn0K_XAcqn0KVm1YkuHfYmhn3rfKVIWYk0A4vTjYsQW0snj0snj0s0AT45HD0uh-zTLwxThNMpyq85Hc0TvNWUv4bgLF-uv-EUWY3n1f0TLPs5Hc0TLPsnWYs0ZwYTjY10AwGTLws5H00mycqn0KWThnqnW64PHf0%26__mobads_cookie%3D%26__mobads_sid%3D723ff9d8572510f2&sn=863637021737296&clk=1";
URL u = new URL(s);
HttpURLConnection openConnection = (HttpURLConnection) u.openConnection();
int responseCode = openConnection.getResponseCode();
InputStream inputStream = openConnection.getInputStream();
System.out.println(responseCode);
catch (MalformedURLException e)
// TODO Auto-generated catch block
e.printStackTrace();
catch (IOException e)
// TODO Auto-generated catch block
e.printStackTrace();

参考技术A HTTP错误码400,代表客户端发起的请求不符合服务器对请求的某些限制,或者请求本身存在一定的错误。
HTTP的错误码302转向可能会有URL规范化及网址劫持的问题。可能被搜索引擎判为可疑转向,甚至认为是作弊。
可能与你的HTTPClient配置和Agent类型版本有关系。

HttpClient 4.4 请求

4.2 版本

 1     /**
 2      * url 请求 paramUrl
 3      * 
 4      * @time 2015年11月10日下午4:40:22
 5      * @packageName com.rom.utils
 6      * @param url         url请求地址
 7      * @param header    请求头信息
 8      * @param params     url请求参数
 9      * @param paramstype 参数类型 1:json格式 ; 其他:正常格式;
10      * @param resulttype 返回值类型 1: 压缩流字符串 2:正常字符串
11      * @return
12      */
13     public synchronized static String paramUrl(String url, Map<String, String> header, Map<String, Object> params,
14             String paramstype, String resulttype) {
15 
16         String result = "";
17         HttpClient httpClient = new DefaultHttpClient();
18         httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
19 
20         HttpPost httpPost = new HttpPost(url);
21 
22         if (header != null) {
23             Set<String> headerkey = header.keySet();
24             Iterator<String> headerkeyit = headerkey.iterator();
25             while (headerkeyit.hasNext()) {
26                 String key = (String) headerkeyit.next();
27                 httpPost.setHeader(key, header.get(key).toString());
28             }
29         }
30 
31         try {
32             // 如果参数类型为1 证明参数传递方式为 json格式
33             if (paramstype != null && paramstype.equals("1")) {
34                 if (params != null) {
35                     StringEntity entity = new StringEntity(JSONObject.fromObject(params).toString(), "utf-8");// 解决中文乱码问题
36                     entity.setContentEncoding("UTF-8");
37                     entity.setContentType("application/json");
38                     httpPost.setEntity(entity);
39                 }
40             } else {
41                 // 参数格式为 键值对形式
42                 if (params != null) {
43                     List<NameValuePair> formparams = new ArrayList<NameValuePair>();
44                     Set<String> keySet = params.keySet();
45                     Iterator<String> keyit = keySet.iterator();
46                     while (keyit.hasNext()) {
47                         String key = (String) keyit.next();
48                         formparams.add(new BasicNameValuePair(key, params.get(key).toString()));
49                     }
50                     UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
51                     httpPost.setEntity(uefEntity);
52                 }
53             }
54 
55             HttpResponse response = httpClient.execute(httpPost);
56             HttpEntity entity = response.getEntity();
57             if (entity != null) {
58                 // 返回类型如果不为空 并且 等于1 证明该返回结果经过zip压缩
59                 if (resulttype != null && resulttype.equals("1")) {
60                     result = EntityUtils.toString(new GzipDecompressingEntity(entity), "utf-8");
61                 } else {
62                     result = EntityUtils.toString(entity, "utf-8");
63                 }
64             }
65         } catch (UnsupportedEncodingException e) {
66             e.printStackTrace();
67             log.error(e.getMessage());
68         } catch (ClientProtocolException e) {
69             e.printStackTrace();
70             log.error(e.getMessage());
71         } catch (IOException e) {
72             e.printStackTrace();
73             log.error(e.getMessage());
74         } finally {
75             httpClient.getConnectionManager().shutdown(); 
76         }
77         return result;
78     }

 

4.4 版本

 1     /**
 2      * url 请求 paramUrl
 3      * 
 4      * @time 2015年11月10日下午4:40:22
 5      * @packageName com.rom.utils
 6      * @param url         url请求地址
 7      * @param header    请求头信息
 8      * @param params     url请求参数
 9      * @param paramstype 参数类型 1:json格式 ; 其他:正常格式;
10      * @return
11      */
12     public  static JSONObject paramUrl(String url ,Map<String, String> header,
13             Map<String, Object> params,String paramstype){
14         
15         RequestConfig config = RequestConfig.custom()
16                 .setConnectionRequestTimeout(10000).setConnectTimeout(10000)
17                 .setSocketTimeout(10000).build();
18         
19         HttpPost httpPost = new HttpPost(url);
20         
21         httpPost.setConfig(config);
22         if (header != null) {
23             Set<String> headerkey = header.keySet();
24             Iterator<String> headerkeyit = headerkey.iterator();
25             while (headerkeyit.hasNext()) {
26                 String key = (String) headerkeyit.next();
27                 httpPost.setHeader(key, header.get(key).toString());
28             }
29         }
30         
31         if (params != null) {
32             // 如果参数类型为1 证明参数传递方式为 json格式
33             if (paramstype != null && paramstype.equals("1")) {
34                 StringEntity entity = new StringEntity(JSONObject.fromObject(params).toString(), "utf-8");// 解决中文乱码问题
35                 entity.setContentEncoding("UTF-8");
36                 entity.setContentType("application/json");
37                 httpPost.setEntity(entity);
38             } else {
39                 // 参数格式为 键值对形式
40                 List<NameValuePair> formparams = new ArrayList<NameValuePair>();
41                 Set<String> keySet = params.keySet();
42                 Iterator<String> keyit = keySet.iterator();
43                 while (keyit.hasNext()) {
44                     String key = (String) keyit.next();
45                     formparams.add(new BasicNameValuePair(key, params.get(key).toString()));
46                 }
47                 UrlEncodedFormEntity uefEntity = null;
48                 try {
49                     uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
50                 } catch (UnsupportedEncodingException e) {
51                     e.printStackTrace();
52                 }
53                 httpPost.setEntity(uefEntity);
54             }
55         }
56         
57         CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(null).build();//设置进去
58         
59         CloseableHttpResponse response = null;
60         StringBuffer out;
61         try {
62             response = httpClient.execute(httpPost); 
63             
64             HttpEntity entity = response.getEntity();
65             
66             InputStream in = entity.getContent();
67             
68             out = new StringBuffer();  
69             byte[] b = new byte[4096];  
70             for (int n; (n = in.read(b)) != -1;) {  
71                 out.append(new String(b, 0, n));  
72             }
73             JSONObject json = JSONObject.fromObject(out.toString());
74             in = null;
75             return json;
76         } catch (ClientProtocolException e) {
77             log.error(e.getMessage());
78         } catch (IllegalStateException e) {
79             log.error(e.getMessage());
80         } catch (IOException e) {
81             log.error(e.getMessage());
82         } finally{
83             try {
84                 if (httpClient!=null) {
85                     httpClient.close();
86                 }
87             } catch (IOException e) {
88                 log.error(e);
89             }
90         }
91         return null;
92     }
93     

 

以上是关于为啥HttpClient请求返回400,URL请求返回302正常的主要内容,如果未能解决你的问题,请参考以下文章

为啥 System.Net.Http HttpClient 对我的请求 URL 进行编码?

第二次调用 C# HttpClient 错误请求

PostMan发送请求参数带有路径特殊字符会返回400错误(与URL字符及URL编码值有关)

PostMan发送请求参数带有路径特殊字符会返回400错误(与URL字符及URL编码值有关)

HTTPClient 返回 400 Bad Request 但 Postman 在 C# 中返回 201

AWS S3 通过预签名 URL 上传返回 400 错误请求