0

我正在尝试更改 HTTPClient 已弃用的代码,但我总是收到 i/o 异常,我不知道我错在哪里。 我不推荐使用的旧代码片段

  public JSONObject getJSONFromUrl(String address, String longUrl) {
     // Making HTTP request
     try {
        // DefaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(address);

        httpPost.setEntity(new StringEntity("{\"longUrl\":\"" + longUrl + "\"}"));
        httpPost.setHeader("Content-Type", "application/json");
        HttpResponse httpResponse = httpClient.execute(httpPost);

        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

我的新不工作代码片段

 try {
    HttpURLConnection httpcon = (HttpURLConnection) ((new          URL(address).openConnection()));
    httpcon.setDoOutput(true);
    httpcon.setRequestProperty("Content-Type", "application/json");
    httpcon.setRequestMethod("POST");
    httpcon.connect();

 //   byte[] outputBytes = "{'value': 7.5}".getBytes("UTF-8");
   is = httpcon.getInputStream();
 /*   os.write(outputBytes);

    os.close();*/
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    catch (Exception e) {
        e.printStackTrace();
    }
4

1 回答 1

0

首先,您需要将参数值发送到您尚未发送的 URL。

 OutputStream out = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
            writer.write(--SENDING PARAMETER HERE--);
            writer.flush();
            writer.close();
            out.close();

然后接下来,使用 bufferedReader 获得响应:

BufferedReader in = new BufferedReader(new InputStreamReader(
                    conn.getInputStream(), "UTF-8"));

并收到如下响应:

while ((inputLine = in.readLine()) != null) 
{
    Log.d("finalResponse: ", inputLine);
}

将 inputLine 数据类型设置为响应的数据类型。确保您发送的参数与 API/URL 设置为接收它的形式完全一致。

是的,不要忘记关闭 BufferedReading 并断开 URLConnection。

in.close();
httpcon.disconnect();

我希望这有帮助。快乐编码。

于 2015-09-02T10:25:37.870 回答