【问题标题】:How to add json array at the end of url in Android using HttpURLConnection?如何使用 HttpURLConnection 在 Android 中的 url 末尾添加 json 数组?
【发布时间】:2016-04-18 12:46:22
【问题描述】:

最近在一个项目中,我不得不面对我同事的一个 API,它使用 GET 方法接受 URL 中对象的 JSON 数组。

比如调用API是

api.site.com/object/create/[{"id":1,"name":"Hello!"},{"id":2,"name":"World!"}]

此 URL 与 Chrome 完美配合,API 返回预期值,例如:[{"id":12501}]

但在 Android 中,处理的函数会抛出一个 java.net.SocketTimeoutException

代码如下:

public String makeMVCServiceCall(String url,Method method,String additionalInformation)

{
    url=url+"/"+additionalInformation;
    return makeServiceCall(url,method);
}
public String makeServiceCall(String url,Method method)
{
    HttpURLConnection connection=null;
    try
    {
        URL u=new URL(url);
        connection=(HttpURLConnection)u.openConnection();
        String m=method== Method.GET?"GET":method== Method.POST?"POST":null;
        connection.setRequestMethod(m);        

        connection.setUseCaches(false);
        connection.setAllowUserInteraction(false);
        connection.setReadTimeout(READ_TIMEOUT);
        connection.setConnectTimeout(CONNECT_TIMEOUT);            
        connection.connect();
        int status=0;
        String response=connection.getResponseMessage();            
        status=connection.getResponseCode();


        switch (status)
        {
            case 200:
            case 201:

                BufferedReader br=new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder sb=new StringBuilder();

                String line;
                while((line=br.readLine())!=null)
                {
                    sb.append(line+"\n");
                }
                br.close();

                return sb.toString();
            default:                    
                return null;
        }
    }

    catch (Exception e)
    {

    }
    finally {
        if(connection!=null)
            try
            {
                connection.disconnect();
            }
            catch (Exception e)
            {

            }
    }

    return null;
}

超时为 5 秒,将其更改为 15 秒并没有任何区别。我认为在 URL 末尾附加 JSON 对象是一种不好的做法,但我必须使用该 API。

有什么建议吗?

【问题讨论】:

  • 永远不要在没有记录的情况下捕获异常。您在代码中的两个位置执行此操作。事实上,目前尚不清楚您如何确定这是SocketTimeoutException
  • 对不起,我在粘贴代码时不得不删除它们。我用 e.getClass() 抓住了他们
  • 您是否正在对该服务器进行任何其他有效的调用? IOW,这个问题是否仅限于这一个请求,还是您可能面临更大的问题,根本无法与服务器通信?
  • 为调用函数makeMVCServiceCall(...)的方法编写代码,因为您粘贴的代码就可以了。应该是url的问题。同时粘贴整个堆栈跟踪
  • 是的,我愿意,还有四个其他请求正在使用此功能,它们运行良好。但是这个不起作用,我尝试使用 URLEncoder 但没有任何改变,有一次我收到 400 Bad Request Error。

标签: java android json gson httpurlconnection


【解决方案1】:

尝试编码附加参数:

URLEncoder.encode(additionalInformation)

【讨论】:

  • 谢谢,但没有任何改变。
  • 您是否在使用代理?如果是,那么您需要设置 jvm 代理:http.proxyHost=[域或 IP] http.proxyPort=[端口号]
  • 不,我的设备直接连接到互联网。
猜你喜欢
  • 2017-06-15
  • 1970-01-01
  • 1970-01-01
  • 2015-04-17
  • 1970-01-01
  • 2019-07-11
  • 1970-01-01
  • 2021-03-09
  • 1970-01-01
相关资源
最近更新 更多