顯示具有 json 標籤的文章。 顯示所有文章
顯示具有 json 標籤的文章。 顯示所有文章

2016年10月1日 星期六

How to use okhttp get the json

How to use okhttp get the json
http://stackoverflow.com/questions/28221555/how-does-okhttp-get-json-string
Create the right object

gson = new Gson();


Build the request

HttpUrl.Builder urlBuilder = HttpUrl.parse("https://api.github.help").newBuilder();
urlBuilder.addQueryParameter("v", "1.0");
urlBuilder.addQueryParameter("user", "vogella");
String url = urlBuilder.build().toString();

Request request = new Request.Builder()
                     .url(url)
                     .build();








OKHTTP3 update UI

client.newCall(request).enqueue(new Callback() {
    @Override
    public void onResponse(Call call, final Response response) throws IOException {
        // ... check for failure using `isSuccessful` before proceeding

        // Read data on the worker thread
        final String responseData = response.body().string();

        // Run view-related code back on the main thread
        MainActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    TextView myTextView = (TextView) findViewById(R.id.myTextView);
                    myTextView.setText(responseData);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
       }
    }
});


2016年1月11日 星期一

Retrofit 2

1.
we wnat to get json from

https://api.stackexchange.com/2.2/search?order=desc&sort=activity&tagged=android&site=stackoverflow

2.

compile 'com.squareup.retrofit2:retrofit:2.0.0-beta3'
    compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta3'

3.

Add the permission to access the Internet to your manifest file.
<uses-permission android:name="android.permission.INTERNET"/>

4.create a approaite class

can use http://www.jsonschema2pojo.org/ to help

public class Item {

    private List<String> tags = new ArrayList<String>();
    private Owner owner;
    private Boolean isAnswered;
    private Integer viewCount;
    private Integer answerCount;
    private Integer score;
    private Integer lastActivityDate;
    private Integer creationDate;
    private Integer questionId;
    private String link;
    private String title;
    private Integer acceptedAnswerId;
    private Integer lastEditDate;

    /**
     *
     * @return
     * The tags
     */
    public List<String> getTags() {
        return tags;
    }

    /**
     *
     * @param tags
     * The tags
     */
    public void setTags(List<String> tags) {
        this.tags = tags;
    }

    /**
     *
     * @return
     * The owner
     */
    public Owner getOwner() {
        return owner;
    }

    /**
     *
     * @param owner
     * The owner
     */
    public void setOwner(Owner owner) {
        this.owner = owner;
    }

    /**
     *
     * @return
     * The isAnswered
     */
    public Boolean getIsAnswered() {
        return isAnswered;
    }

    /**
     *
     * @param isAnswered
     * The is_answered
     */
    public void setIsAnswered(Boolean isAnswered) {
        this.isAnswered = isAnswered;
    }

    /**
     *
     * @return
     * The viewCount
     */
    public Integer getViewCount() {
        return viewCount;
    }

    /**
     *
     * @param viewCount
     * The view_count
     */
    public void setViewCount(Integer viewCount) {
        this.viewCount = viewCount;
    }

    /**
     *
     * @return
     * The answerCount
     */
    public Integer getAnswerCount() {
        return answerCount;
    }

    /**
     *
     * @param answerCount
     * The answer_count
     */
    public void setAnswerCount(Integer answerCount) {
        this.answerCount = answerCount;
    }

    /**
     *
     * @return
     * The score
     */
    public Integer getScore() {
        return score;
    }

    /**
     *
     * @param score
     * The score
     */
    public void setScore(Integer score) {
        this.score = score;
    }

    /**
     *
     * @return
     * The lastActivityDate
     */
    public Integer getLastActivityDate() {
        return lastActivityDate;
    }

    /**
     *
     * @param lastActivityDate
     * The last_activity_date
     */
    public void setLastActivityDate(Integer lastActivityDate) {
        this.lastActivityDate = lastActivityDate;
    }

    /**
     *
     * @return
     * The creationDate
     */
    public Integer getCreationDate() {
        return creationDate;
    }

    /**
     *
     * @param creationDate
     * The creation_date
     */
    public void setCreationDate(Integer creationDate) {
        this.creationDate = creationDate;
    }

    /**
     *
     * @return
     * The questionId
     */
    public Integer getQuestionId() {
        return questionId;
    }

    /**
     *
     * @param questionId
     * The question_id
     */
    public void setQuestionId(Integer questionId) {
        this.questionId = questionId;
    }

    /**
     *
     * @return
     * The link
     */
    public String getLink() {
        return link;
    }

    /**
     *
     * @param link
     * The link
     */
    public void setLink(String link) {
        this.link = link;
    }

    /**
     *
     * @return
     * The title
     */
    public String getTitle() {
        return title;
    }

    /**
     *
     * @param title
     * The title
     */
    public void setTitle(String title) {
        this.title = title;
    }

    /**
     *
     * @return
     * The acceptedAnswerId
     */
    public Integer getAcceptedAnswerId() {
        return acceptedAnswerId;
    }

    /**
     *
     * @param acceptedAnswerId
     * The accepted_answer_id
     */
    public void setAcceptedAnswerId(Integer acceptedAnswerId) {
        this.acceptedAnswerId = acceptedAnswerId;
    }

    /**
     *
     * @return
     * The lastEditDate
     */
    public Integer getLastEditDate() {
        return lastEditDate;
    }

    /**
     *
     * @param lastEditDate
     * The last_edit_date
     */
    public void setLastEditDate(Integer lastEditDate) {
        this.lastEditDate = lastEditDate;
    }


}




public class Question {

    String title;
    String link;

    @Override
    public String toString() {
        return(title);
    }

}



4.

Define the REST API for Retrofit via the following interface.

public interface StackOverflowAPI {
    @GET("/2.2/questions?order=desc&sort=creation&site=stackoverflow")
    Call<StackOverflowQuestions> loadQuestions(@Query("tagged") String tags);



more detail can see http://square.github.io/retrofit/

5. use Retrofit class generates an implementation of the interface.

Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl("https://api.stackexchange.com")
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
            StackOverflowAPI stackOverflowAPI = retrofit.create(StackOverflowAPI.class);

            

6. make a asynchronous HTTP request to the remote webserver


Call<StackOverflowQuestions> call = stackOverflowAPI.loadQuestions("android");
            //asynchronous call
            Response<StackOverflowQuestions> qo=null;
            

               qo = call.execute();

7.get the body to use

qo.body();


other method

 call.enqueue(new Callback<Bank>() {
            @Override
            public void onResponse(Response<Bank> response) {
                Bank bank = response.body();
            }

            @Override
            public void onFailure(Throwable t) {

            }

        });




2015年11月4日 星期三

JSON in JAVA

1.Make the JSON more beautiful


https://jsonformatter.curiousconcept.com/

2. if we have the JSON content

{"city":{"id":3093133,"name":"Lodz","coord":{"lon":19.466669,"lat":51.75},"country":"PL","population":0},"cod":"200","message":0.0342,"cnt":7,"list":[{"dt":1446631200,"temp":{"day":4.92,"min":-0.39,"max":8.24,"night":-0.39,"eve":6.36,"morn":0},"pressure":1022.08,"humidity":80,"weather":[{"id":800,"main":"Clear","description":"sky is clear","icon":"01d"}],"speed":3.22,"deg":258,"clouds":0},{"dt":1446717600,"temp":{"day":5.21,"min":-1.21,"max":8.19,"night":2.32,"eve":6.73,"morn":-1.21},"pressure":1024.42,"humidity":87,"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03d"}],"speed":2.01,"deg":106,"clouds":36},{"dt":1446804000,"temp":{"day":4.36,"min":-1.3,"max":7.92,"night":4.97,"eve":7.28,"morn":0.46},"pressure":1024.22,"humidity":86,"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10d"}],"speed":1.97,"deg":228,"clouds":0,"rain":2.62},{"dt":1446890400,"temp":{"day":11.87,"min":7.09,"max":12.61,"night":11.64,"eve":12.61,"morn":7.09},"pressure":1020.33,"humidity":0,"weather":[{"id":501,"main":"Rain","description":"moderate rain","icon":"10d"}],"speed":3.46,"deg":231,"clouds":94,"rain":5.34},{"dt":1446976800,"temp":{"day":14.08,"min":9.52,"max":14.08,"night":9.52,"eve":13.85,"morn":11.8},"pressure":1013.83,"humidity":0,"weather":[{"id":501,"main":"Rain","description":"moderate rain","icon":"10d"}],"speed":5.22,"deg":226,"clouds":99,"rain":4.43},{"dt":1447063200,"temp":{"day":9.64,"min":5.93,"max":9.64,"night":5.93,"eve":8.59,"morn":8.38},"pressure":1016.45,"humidity":0,"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10d"}],"speed":8.81,"deg":284,"clouds":51,"rain":2.43},{"dt":1447149600,"temp":{"day":12.77,"min":6.13,"max":14.46,"night":14.46,"eve":14.18,"morn":6.13},"pressure":1005.35,"humidity":0,"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10d"}],"speed":7.09,"deg":225,"clouds":94,"rain":1.01}]}


we want to get the first day mix temp



JSONObject jsonObject = new JSONObject(weatherJsonStr);
        JSONArray jaLIST=(JSONArray)jsonObject.get("list");
       JSONObject joDay=jaLIST.getJSONObject(0);
        double max=joDay.getJSONObject("temp").getDouble("max");





2015年11月2日 星期一

example of send The HTTP request and read the HTTP response

 A goode website for JAVA IO

http://tutorials.jenkov.com/java-io/overview.html


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


           

 // These two need to be declared outside the try/catch
            // so that they can be closed in the finally block.
            HttpURLConnection urlConnection = null;
            BufferedReader reader = null;

            // Will contain the raw JSON response as a string.
            String forecastJsonStr = null;

            try {
                // Construct the URL for the OpenWeatherMap query
                // Possible parameters are avaiable at OWM's forecast API page, at
                // http://openweathermap.org/API#forecast
                Uri.Builder builder = new Uri.Builder();
                builder.scheme("http")
                        .authority("api.openweathermap.org")
                        .appendPath("data")
                        .appendPath("2.5")
                        .appendPath("forecast")
                        .appendPath("daily")
                        .appendQueryParameter("q", potoalCode + "")
                        .appendQueryParameter("mode", "json")
                        .appendQueryParameter("units", "metric")
                        .appendQueryParameter("cnt", "7")
                        .appendQueryParameter("appid", APPID);
                String myUrl = builder.build().toString();


                URL url = new URL(myUrl);

                // Create the request to OpenWeatherMap, and open the connection
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();

                // Read the input stream into a String
                InputStream inputStream = urlConnection.getInputStream();
                StringBuffer buffer = new StringBuffer();
                if (inputStream == null) {
                    // Nothing to do.
                    return null;
                }
                reader = new BufferedReader(new InputStreamReader(inputStream));

                String line;
                while ((line = reader.readLine()) != null) {
                    // Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
                    // But it does make debugging a *lot* easier if you print out the completed
                    // buffer for debugging.
                    buffer.append(line + "\n");
                }

                if (buffer.length() == 0) {
                    // Stream was empty.  No point in parsing.
                    return null;
                }
                forecastJsonStr = buffer.toString();
            } catch (IOException e) {
                Log.e("PlaceholderFragment", "Error ", e);
                // If the code didn't successfully get the weather data, there's no point in attemping
                // to parse it.
                return null;
            } finally{
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (final IOException e) {
                        Log.e("PlaceholderFragment", "Error closing stream", e);
                    }
                }
            }