2017-10-14 1 views
-1

私は過去数日間、Web APIから成功したJSON呼び出しを取得しようとしています。私は成功していない複数のAPIを試したので、API自体ではないと思いますが、どうすればHttpURLConnectionで呼び出すことができますか?HttpURLConnectionを使用してJSONレスポンス用のWeb APIでGETリクエストを使用するにはどうすればよいですか?

​​

私が続き、これは無駄で動作するように取得しようと、複数のチュートリアルとガイドを使用しています。ここ

は、私のコードの剪定バージョンです。私はまた、BufferedReaderとStringBuilderを使用して、データを無駄にすることを試みました。

EDIT:

public class NetworkConnect { 

/** 
* Execute the given URI, and return the data from that URI. 
* 
* @param uri the universal resource indicator for a set of data. 
* @return the set of data provided by the uri 
*/ 

    private Exception exception; 

    HttpURLConnection connection = null; 
    BufferedReader reader = null; 
    protected String doInBackground(String urlString) { 
     try { 

      URL url = new URL(urlString); 
      connection = (HttpURLConnection) url.openConnection(); 
      connection.connect(); 


      InputStream stream = connection.getInputStream(); 

      reader = new BufferedReader(new InputStreamReader(stream)); 

      StringBuffer buffer = new StringBuffer(); 
      String line = ""; 

      while ((line = reader.readLine()) != null) { 
       buffer.append(line+"\n"); 
       Log.d("Response: ", "> " + line); //here u ll get whole response...... :-) 

      } 

      return buffer.toString(); 


     } catch (Exception e) { 
      e.printStackTrace(); 
     }finally { 
      if (connection != null) { 
       connection.disconnect(); 
      } 
      try { 
       if (reader != null) { 
        reader.close(); 
       } 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
     return null; 
    } 

} 
+0

あなたがいずれかを呼び出す必要がありますメインスレッドではないネットワーク要求 –

+1

[どうすればandroid.os.NetworkOnMainThreadExceptionを修正できますか?](https://stackoverflow.com/questions/6343166/how-do-i-fix-android-os-networkonmainthreadexception) –

+0

私はこの解決策を試したそれはうまくいかなかった。 – fangzthewolf

答えて

0

ちょうどdoInBackground()内のネットワーク運用を行うために、AsyncTaskのサブクラスを使用します。私はノー成功に過去にも同様に別のクラスにそれを作ったしている

メソッドオーバーライドはバックグラウンドスレッド上で実行されます。次に、結果をonPostExecute()メソッドオーバーライドに渡します。これはUIスレッドで実行されます。ここで

何が必要ありませんAsyncTaskを持つシンプルな活動です:

public class TestActivity extends AppCompatActivity { 

    TextView textView; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_test); 

     textView = (TextView) findViewById(R.id.textView); 

     new NetworkConnect().execute(); 
    } 

    class NetworkConnect extends AsyncTask<Void, Void, JSONObject> { 

     private static final String JSON_URL = "http://ip.jsontest.com/"; 
     String charset = "UTF-8"; 
     HttpURLConnection conn; 
     StringBuilder result; 
     URL urlObj; 

     @Override 
     protected JSONObject doInBackground(Void... args) { 

      JSONObject retObj = null; 

      try { 
       urlObj = new URL(JSON_URL); 

       conn = (HttpURLConnection) urlObj.openConnection(); 
       conn.setDoOutput(false); 
       conn.setRequestMethod("GET"); 
       conn.setRequestProperty("Accept-Charset", charset); 
       conn.setConnectTimeout(15000); 
       conn.connect(); 

       //Receive the response from the server 
       InputStream in = new BufferedInputStream(conn.getInputStream()); 
       BufferedReader reader = new BufferedReader(new InputStreamReader(in)); 
       result = new StringBuilder(); 
       String line; 
       while ((line = reader.readLine()) != null) { 
        result.append(line); 
       } 

       Log.d("NetworkConnect", "result: " + result.toString()); 

       retObj = new JSONObject(result.toString()); 

      } catch (IOException e) { 
       e.printStackTrace(); 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 

      return retObj; 
     } 

     @Override 
     protected void onPostExecute(JSONObject json) { 
      //Use JSON result to display in TextView 
      if (json != null) { 
       textView.setText(json.toString()); 
      } 
     } 
    } 
} 

は注:のAndroidManifest.xmlでINTERNET権限を持っていることを確認してください。

<uses-permission android:name="android.permission.INTERNET" /> 
+0

これはうまくいきました、ありがとうございました。 – fangzthewolf

関連する問題