在Android中连接到远程网站(在PHP中)时出现连接错误

时间:2016-09-12 16:30:17

标签: php android json

我正在尝试设计一个URL Shortener应用程序,它是我的web-app(Link Here)的扩展。问题是,当我尝试连接到我的网站时(使用HttpURLConnection类)&解析JSON响应,它会抛出异常。 (我还设计了一个mini-api,在传递正确的URL时返回JSON响应)

代码(产生问题):

private String getResponseText(String param) throws IOException
{
    StringBuilder response  = new StringBuilder();
    URL url = new URL("http://<THE-URL>/shorten-api.php?url="+param);
    HttpURLConnection httpconn = (HttpURLConnection)url.openConnection();

    BufferedReader input = new BufferedReader(new InputStreamReader(httpconn.getInputStream()),8192);
    String strLine = null;
    while ((strLine = input.readLine()) != null)
    {
        response.append(strLine);
    }
    input.close();
    return response.toString();
}

使用的参考:My Reference

1 个答案:

答案 0 :(得分:0)

我找到了解决方法:使用HttpGet API(已弃用,但非常方便)。

StringBuffer sb = new StringBuffer("");
    String line = "";
    try{
        String longUrl = (String) params[0];
        String link = "http://<SHORTENER_URL>/shorten-api.php?url="+longUrl;
        URL url = new URL(link);
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet();
        request.setURI(new URI(link));
        HttpResponse response = client.execute(request);
        BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        while((line = in.readLine()) != null)
        {
            sb.append(line);
            break;
        }
        in.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
    Log.d("SHORT URL",sb.toString());
    return sb.toString();

然后,我从This:

访问了提取的字符串
new ShortenAPIConnector(getApplicationContext()).execute(lUrl).get();

感谢您的帮助。