java - HttpURLConnection 响应不工作

标签 java android httpurlconnection

在我的项目中我有 url 喜欢:

localhost:8080/myproject/examples/12

它包含 Json 值..要访问此字段需要将访问 key 作为标题。

现在,我所做的是:

private String doHttpUrlConnectionAction(String desiredUrl)
  throws Exception
  {
    URL url = null;
    BufferedReader reader = null;
    StringBuilder stringBuilder;

    try
    {
      // create the HttpURLConnection
      url = new URL(desiredUrl);
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();

      // just want to do an HTTP GET here
      connection.setRequestMethod("GET");
     // connection.setRequestProperty("Content-Type","application/json");
      connection.setRequestProperty("API-KEY", "value");

      // uncomment this if you want to write output to this url
      connection.setDoOutput(true);

      // give it 15 seconds to respond
      connection.setReadTimeout(15*1000);
      connection.connect();

      // read the output from the server
     // reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));


      StringBuilder sb = new StringBuilder();
      BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
      String line;
      while ((line = rd.readLine()) != null) {
          sb.append(line);
      }
      return sb.toString();

    }
    catch (Exception e)
    {
      e.printStackTrace();
      throw e;
    }
    finally
    {
      // close the reader; this can throw an exception too, so
      // wrap it in another try/catch block.
      if (reader != null)
      {
        try
        {
          reader.close();
        }
        catch (IOException ioe)
        {
          ioe.printStackTrace();
        }
      }
    }
  }

此代码返回输出:

Response Code : 200
<table border="0" cellpadding="4" cellspacing="0"><thead><tr><th>status</th><th>statusCode</th><th>data</th></tr></thead><tbody><tr><td statusCode="200" status="1">Array</td></tr></tbody></table>

但是当我在 httclient 中访问这段代码时,我得到了正确的值..

public String ReadHttpResponse(String url){
      StringBuilder sb= new StringBuilder();
      HttpClient client= new DefaultHttpClient();     
      HttpGet httpget = new HttpGet(url);  
      httpget.addHeader("API-KEY", "value");
      try {
          HttpResponse response = client.execute(httpget);
          StatusLine sl = response.getStatusLine();
          int sc = sl.getStatusCode();
          if (sc==200)
          {
              HttpEntity ent = response.getEntity();
              InputStream inpst = ent.getContent();
              BufferedReader rd= new BufferedReader(new InputStreamReader(inpst));
              String line;
              while ((line=rd.readLine())!=null)
              {
                  sb.append(line);
              }
             // System.out.println(sb.toString());

          }
          else
          {
              System.out.println("I didn't  get the response!");


          }
      } catch (ClientProtocolException e) {
          e.printStackTrace();
      } catch (IOException e) {
          e.printStackTrace();
      }
      return sb.toString();
  }

在这里,我得到了正确的输出..

HttpUrlConnection 哪里出了问题??我在这里做错了什么?我必须使用 HttpUrlConnection。请大家帮帮我..

最佳答案

您可以为请求 POST 和 GET 创建这样的代码逻辑。它有助于降低代码复杂性。您可以为此创建一个方法,并根据 GET 和 POST 方法的需要将参数传递给它。

  HttpURLConnection urlConnection = null;
    try {
        // http client

        murl=new URL(url);
        urlConnection = (HttpURLConnection) murl.openConnection();

        urlConnection.setRequestProperty("Content-Type", "application/json;odata=verbose");
        urlConnection.setRequestProperty("Accept", "application/json;odata=verbose");

        // Checking http request method type
        if (method == POST) {
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);



            if(!jsondata.equals("null")) {
                OutputStream os = urlConnection.getOutputStream();
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(os, "UTF-8"));
                writer.write(jsondata);
                writer.flush();
                writer.close();
                os.close();
            }


        } else if (method == GET) {
            // appending params to url
            urlConnection.setRequestMethod("GET");

        }
        resCode = urlConnection.getResponseCode();
        Log.i("TAG", "response code=>" + resCode);

关于java - HttpURLConnection 响应不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38581760/

相关文章:

mouseevent - mouseReleased 和 mouseClicked 之间的区别

android - 为什么 FusedLocationProviderApi 从不报告精度优于 10m?这有记录吗?

java.net.SocketException : Address family not supported by protocol in android emulator 异常

java - Android模拟器访问IIS Express

java - 用 O(nlogn) 时间 O(1) 空间有效地计算数组中等值对的数量

java - 不在 Logger 控制台中打印日志

java - 'the local character set' 与 'the encoding of the text data you want to process' 相同吗?

android - 圆角后可塑 ImageView 上的黑边

java - 如何让HttpURLConnection超时?

java - 使用 HttpURLConnection 发送二进制数据