[JAVA] [MT] Geben Sie die Artikelkategorie von Android mit Daten-API an

DataAPI möchte Artikel auf Android veröffentlichen! Es ist zu dieser Zeit eine sehr wichtige API. Dieses Mal möchte ich kurz die Spezifikation der Kategorien unter ihnen erläutern.

Artikelkategorie abrufen

MainActivity.java

package com.example.mtapply01;

import java.util.ArrayList;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;

import com.loopj.android.http.*;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.json.*;

import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity  {
    MainActivity act;
    Button btnSend;
    TextView txtTitle, txtBody;

    String cgi_url  = "http://path/to/mt-data-api.cgi";
    String blog_id  = "id";
    String username = "username";
    String password = "password";
    String token;
    ArrayList<String>  categoryLabel;
    ArrayList<Integer> categoryId;
    AsyncHttpClient    client;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        act = this;
        btnSend = (Button) findViewById(R.id.btnSend);
        txtTitle = (TextView) findViewById(R.id.txtTitle);
        txtBody = (TextView) findViewById(R.id.txtBody);

        categoryLabel        = new ArrayList<String>();
        categoryId           = new ArrayList<Integer>();
        client               = new AsyncHttpClient();
        RequestParams params = new RequestParams();

        params.put("username", username);
        params.put("password", password);
        params.put("clientId", "test");

        String url = cgi_url.concat("/v2/authentication");
        client.post(url, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(JSONObject res) {
                try {
                    token = res.getString("accessToken");
                    Toast.makeText(act, "Sie sind jetzt angemeldet", Toast.LENGTH_LONG).show();
                } catch (Exception e) {
                    Toast.makeText(act, "Login Fehler", Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFailure(Throwable e, JSONObject res) {
                Toast.makeText(act, "Login Fehler", Toast.LENGTH_LONG).show();
            }
        });

        url = cgi_url.concat("/v2/sites/2/categories");
        client.get(url, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(JSONObject json) {
                try {
                    //Um den Titel zu bekommen
                    JSONArray datas = json.getJSONArray("items");
                    for (int i = 0; i < datas.length(); i++) {
                        categoryLabel.add(datas.getJSONObject(i).getString("label"));
                        categoryId.add(Integer.parseInt(datas.getJSONObject(i).getString("id")));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Throwable e, JSONObject res) {
                Toast.makeText(act, "Login Fehler", Toast.LENGTH_LONG).show();
            }
        });



        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Post entry
                try {
                    uploadText();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }


    private void uploadText() throws JSONException {
        CharSequence  title  = "title";
        CharSequence  body   = "body";
        JSONObject    entry  = new JSONObject();
        RequestParams params = new RequestParams();
        JSONArray categories = new JSONArray();
        JSONObject category;
        for(int i=0; i<categoryLabel.size(); i++) {
            category = new JSONObject();
            category.put("id",categoryId.get(i));
            categories.put(category);
        }
        try {
            entry.put("title", title);
            entry.put("body", body);
            entry.put("categories",categories);
            entry.put("status", "Draft");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        params.put("entry", entry.toString());
        String url = cgi_url.concat("/v2/sites/").concat(blog_id).concat("/entries");
        Header[] headers = new Header[1];
        headers[0] = new BasicHeader("X-MT-Authorization", "MTAuth accessToken=".concat(token));
        client.post(getBaseContext(), url, headers, params, "application/x-www-form-urlencoded", new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(JSONObject res) {
                Toast.makeText(act, "vollständig senden", Toast.LENGTH_LONG).show();
            }
            public void onFailure(Throwable e, JSONObject res) {
                Toast.makeText(act, "Sendefehler", Toast.LENGTH_LONG).show();
            }
        });

    }


    private void setButtonEnable(boolean flagEnable){
        btnSend.setEnabled(flagEnable);
    }

    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#eeeeee"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Titel" />

    <EditText
        android:id="@+id/txtTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/textView1"
        android:background="#ffffff"
        android:ems="10"
        android:inputType="text"
        android:padding="3dp" >

        <requestFocus />
    </EditText>

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/txtTitle"
        android:layout_marginTop="16dp"
        android:text="Text"
        android:textAppearance="?android:attr/textAppearanceSmall" />

    <EditText
        android:id="@+id/txtBody"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/textView2"
        android:background="#ffffff"
        android:ems="10"
        android:gravity="center_vertical|top"
        android:inputType="textMultiLine"
        android:padding="3dp"
        android:layout_above="@+id/btnSend" />

    <Button
        android:id="@+id/btnSend"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:text="Senden"
        />


</RelativeLayout>

Deklarieren Sie "cgi_url: DataAPI-Endpunkt", "blog_id: blog ID", "Benutzername: Benutzername", "Passwort: Passwort" im Mitgliederbereich.

Sie können Artikel in onCreate erhalten.

Um sich anzumelden, fügen Sie die Mitgliedsvariablen "Benutzername" und "Passwort" in "RequestParams" ein und ** posten ** mit "AsyncHttpClient" in "cgi_url + / v2 / authentication".

Wenn Sie sich erfolgreich anmelden, geben Sie "onSuccess" ein und "JSONObject" wird zurückgegeben. Speichern Sie also das "accessToken".

Um die Artikelkategorie zu erhalten, ** poste ** die zuvor erstellten "RequestParams" in "cgi_url + / v2 / sites / 2 / category" mit "AsyncHttpClient".

Wenn die Kategorie erfolgreich erworben wurde, wird "onSuccess" eingegeben. Fügen Sie daher das Element "items" in "JSONArray" ein.

JSONArray datas = json.getJSONArray("items");

Holen Sie sich das "Label" und die "ID" der registrierten Kategorie aus den erhaltenen "Artikeln".

for(int i=0; i<datas.length(); i++) {
    categoryLabel.add(datas.getJSONObject(i).getString("label"));
    categoryId.add(Integer.parseInt(datas.getJSONObject(i).getString("id")));
}

Jetzt können Sie die Artikelkategorie erhalten.

Artikel posten

Wenn Sie dies tun können, müssen Sie nur noch posten.

    private void uploadText() throws JSONException {
        CharSequence  title  = "title";
        CharSequence  body   = "body";
        JSONObject    entry  = new JSONObject();
        RequestParams params = new RequestParams();
        JSONArray categories = new JSONArray();
        JSONObject category;
        for(int i=0; i<categoryLabel.size(); i++) {           
            category = new JSONObject();
            category.put("id",categoryId.get(i));
            categories.put(category);
        }
        try {
            entry.put("title", title);
            entry.put("body", body);
            entry.put("categories",categories);
            entry.put("status", "Draft");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        params.put("entry", entry.toString());
        String url = cgi_url.concat("/v2/sites/").concat(blog_id).concat("/entries");
        Header[] headers = new Header[1];
        headers[0] = new BasicHeader("X-MT-Authorization", "MTAuth accessToken=".concat(token));
        client.post(getBaseContext(), url, headers, params, "application/x-www-form-urlencoded", new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(JSONObject res) {
                Toast.makeText(act, "vollständig senden", Toast.LENGTH_LONG).show();
            }
            public void onFailure(Throwable e, JSONObject res) {
                Toast.makeText(act, "Sendefehler", Toast.LENGTH_LONG).show();
            }
        });

    }

Erstellen Sie zunächst das Eintragselement "JSONObject" und "RequestParams", um die Artikelanforderung zu senden. Bereiten Sie danach ein JSONArray zum Einfügen mehrerer Kategorien und ein JSONObject zum Einfügen einzelner Kategorien vor. Der Kategorieeintrag ist id und der Kategoriegruppeneintrag ist Kategorien. Wenn ** post **, senden Sie durch Einfügen von "Kategorie" in "Kategorien". Wenn Sie danach den Endpunkt von "url" und "headers" eingeben, der mit "AsyncHttpClient" als "params" festgelegt wurde, und ihn senden, können Sie einen Artikel mit der registrierten Kategorie erstellen.

Ergänzung

Da es das Internet nutzt, ist es in Android Manifest <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> Vergiss nicht zu deklarieren!

Impressionen

Möchten Sie es von Ihrem Chef machen? Ich habe es zum ersten Mal bei Qiita gepostet, als ich gefragt wurde! Es tut mir leid, dass der Inhalt zu schäbig ist. .. .. Ich werde mein Bestes geben, wenn ich das nächste Mal schreibe!

Recommended Posts

[MT] Geben Sie die Artikelkategorie von Android mit Daten-API an
[MT] Geben Sie die Artikelkategorie von Android mit Daten-API an
Versuchen Sie es mit der Emotion API von Android
Kompatibel mit Android 10 (API 29)
Lassen Sie das Armbandgerät mit Bluetooth über die Android-App vibrieren
Android-Entwicklung - WEB-Zugriff (GET) Versuchen Sie, Daten durch Kommunikation mit der Außenwelt abzurufen. ~
Rufen Sie die Microsoft Emotion API auf, indem Sie Bilddaten direkt von Java senden.
SetCookie von der Client-Seite mit OkHttp3
Datenverarbeitung mit der Stream-API von Java 8
Rufen Sie die Salesforce REST-API von Java aus auf
Finden Sie Raspberry Pi von Android mit mDNS
Android Development-WEB Access (POST) Versuchen Sie, mit der Außenwelt zu kommunizieren und Daten zu senden. ~