【问题标题】:Cannot establish HttpURLConnection in Android无法在 Android 中建立 HttpURLConnection
【发布时间】:2013-06-14 03:46:43
【问题描述】:
URL url = new URL(versionPath);
Toast.makeText(getApplicationContext(), versionPath, Toast.LENGTH_SHORT).show();
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();

Toast.makeText(getApplicationContext(), "HttpURLConnection Complete!", Toast.LENGTH_SHORT).show();

异常捕获,第一个版本路径文本正确,看不到“HttpURLConnection Complete!”文本。当我在设备内的浏览器上复制相同的“versionPath”时,我可以看到内容。我的清单中有 INTERNET 权限。有什么想法吗?

【问题讨论】:

标签: android http


【解决方案1】:

这对我有用,我相信所有的类都是 android 的一部分,并且没有使用外部库。

public static JSONObject getJsonFromUrl(String urlString) throws UnsupportedEncodingException, IllegalStateException, IOException, JSONException {
    // set the connection timeout value to 10 seconds (10000 milliseconds)
    final HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, 10000); //how long to wait for connection
    HttpConnectionParams.setSoTimeout(httpParams, 10000); //how long to wait for response
    // Create a new HTTP Client
    DefaultHttpClient defaultClient = new DefaultHttpClient(httpParams);
    // Setup the get request
    HttpGet httpGetRequest = new HttpGet(urlString);
    // Execute the request in the client
    HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
    // Grab the response
    BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
    StringBuilder json = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        json.append(line);
    }

    // Instantiate a JSON object from the request response
    JSONObject jsonObject = new JSONObject(json.toString());

    return jsonObject;
}

【讨论】:

    猜你喜欢
    • 2016-06-13
    • 2017-03-10
    • 1970-01-01
    • 2015-02-09
    • 2015-11-12
    • 2020-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多