使用httpclient 报错问题

加贝先生 发布于 2016/09/26 15:44
阅读 1K+
收藏 0

 Illegal character in query at index 130: 

http://113.240.245.91:8080/gxxtwhservice/oauth2-server/oauth2/userRegister?access_token=a84776ed393589e1d9e7833e7493b558&paramMap={"userName":"%E8%B4%BA%E8%BE%BE","card": "430211199606040017","password": "123456","address": "%E6%B9%96%E5%8D%97%E7%9C%81"}

能否帮忙解答一下 我这一串url哪个字符有问题?  为啥我放浏览器上 访问可以成功访问

加载中
0
高龄购物车驾驶员
高龄购物车驾驶员
这个是发送post请求的示例代码,参数是url和json字符串
public static String doPost(String apiUrl, Object json)
    {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String httpStr = null;
        HttpPost httpPost = new HttpPost(apiUrl);
        CloseableHttpResponse response = null;

        try
        {
            httpPost.setConfig(requestConfig);
            StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");// 解决中文乱码问题
            stringEntity.setContentEncoding("UTF-8");
            stringEntity.setContentType("application/json");
            httpPost.setEntity(stringEntity);
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            System.out.println(response.getStatusLine().getStatusCode());
            httpStr = EntityUtils.toString(entity, "UTF-8");
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (response != null)
            {
                try
                {
                    EntityUtils.consume(response.getEntity());
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
        return httpStr;
    }



0
skhuhu
skhuhu
 你用的get吗· 参数不是这样直接拼接的吧
加贝先生
是用的get啊 get不是这样拼接吗?
0
高龄购物车驾驶员
高龄购物车驾驶员
需要把paramMap后面的json字符串进行url编码
加贝先生
编码了之后 接收方就接不到 参数了。。
0
雨翔河
雨翔河

改一下你请求的ua,改为正常一点的ua,比如:User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36

0
szwx855
szwx855

我觉得你应该改成POST

然后提交数据为:

{"userName":"%E8%B4%BA%E8%BE%BE","card": "430211199606040017","password": "123456","address": "%E6%B9%96%E5%8D%97%E7%9C%81"}

URL为:

http://113.240.245.91:8080/gxxtwhservice/oauth2-server/oauth2/userRegister?access_token=a84776ed393589e1d9e7833e7493b558


这样我觉得比较合理,我还没见过GET时,带了一堆JSON的。这样有点搓。。


加贝先生
post 请求 加参数的时候 如何转成json格式把参数
加贝先生
能给下 post请求的案例吗 谢谢
0
szwx855
szwx855
/**
使用方法:
JSONObject param = new JSONObject();
json.put("a",1);
...

String e = HttpClient.sendByPost(this.portUrl, param.toString(), 30000);

*/
package com.suning.framework.uaa.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 建立Http请求操作的封装类
 *
 * @author L.J.W
 */

public class HttpClient {

    private static final Logger LOGGER = Logger.getLogger(HttpClient.class.getName());

    public static final String CONTENT_TYPE_FORM = "application/x-www-form-urlencoded";

    private static final String HTTP_METHOD_POST = "POST";

    private static final String HTTP_HEADER_CONTENT_TYPE = "Content-Type";

    private static final int HTTP_RESPONSE_CODE_FLAG = 300;

    /**
     * 通过POST请求方式发送<br>
     *
     * @param url     请求URL
     * @param param   请求参数
     * @param timeout 超时时间
     * @return 发送成功与否
     * @throws IOException
     */
    public static String sendByPost(String url, String param, int timeout) throws IOException {
        URLConnection connection = new URL(url).openConnection(Proxy.NO_PROXY);
        HttpURLConnection con = (HttpURLConnection) connection;
        prepareConnection(con, timeout, HTTP_METHOD_POST);
        con.getOutputStream().write(param.getBytes());
        con.getOutputStream().flush();
        con.getOutputStream().close();
        validateResponse(con);
        InputStream responseBody = readResponseBody(con);
        return readResult(responseBody);
    }

    /**
     * 设置HTTP连接相关参数<br>
     *
     * @param connection http连接对象
     * @param timeout    超时时间
     * @param method     请求方式
     * @throws IOException
     */
    private static void prepareConnection(HttpURLConnection connection, int timeout, String method) throws IOException {
        if (timeout >= 0) {
            connection.setConnectTimeout(timeout);
        }
        if (timeout >= 0) {
            connection.setReadTimeout(timeout);
        }
        connection.setDoOutput(true);
        connection.setRequestMethod(method);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setRequestProperty(HTTP_HEADER_CONTENT_TYPE, CONTENT_TYPE_FORM);
    }

    /**
     * 验证响应结果 <br>
     *
     * @param con HTTP连接对象
     * @throws IOException
     */
    private static void validateResponse(HttpURLConnection con) throws IOException {
        if (con.getResponseCode() >= HTTP_RESPONSE_CODE_FLAG) {
            try {
                InputStream es = con.getErrorStream();
                if (es != null) {
                    LOGGER.log(Level.WARNING, "Did not receive successful HTTP response," +
                            "response content is " + readResult(es));
                }
            } catch (Exception ex) {
                LOGGER.log(Level.WARNING, "Exception occur when process errorStream", ex);
            }
            throw new IOException("Did not receive successful HTTP response: status code = " + con.getResponseCode()
                    + ", status message = [" + con.getResponseMessage() + "]");
        }
    }

    /**
     * 读取响应内容 <br>
     *
     * @param con HTTP连接对象
     * @return 响应内容输入流
     * @throws IOException
     */
    private static InputStream readResponseBody(HttpURLConnection con) throws IOException {
        // Plain response found.
        return con.getInputStream();
    }

    /**
     * 解析响应内容 <br>
     *
     * @param is 响应内容输入流
     * @return 响应内容(true/false)
     * @throws IOException
     */
    private static String readResult(InputStream is) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        try {
            StringBuilder temp = new StringBuilder();
            String line = reader.readLine();
            while (line != null && line != "") {
                temp.append(line);
                line = reader.readLine();
            }
            return temp.toString();
        } finally {
            reader.close();
        }
    }

}


希望被采纳哦。



0
loyal
loyal

你后面的参数转下码应该就好了.

止于其他人说post的都是瞎扯淡的.

loyal
loyal
回复 @szwx855 : 不知你哪看出来是大数据量了.只能说你用过的第三方接口太少了.
szwx855
szwx855
你大数据量的json都是转码然后通过get给服务端?在逗我么?
返回顶部
顶部