2016-07-04 19 views
1

Ich arbeite derzeit mit einer App, die auf ein Online-Spiel zugreifen können, um Informationen über mein Konto zu erhalten. Ich muss JSON verwenden, um mit dem Server zu kommunizieren. Ich habe den folgenden Code verwendet, um zu versuchen, mit dem Server zu kommunizieren, aber es gibt keine Antworten vom Server. Ich bemerkte auch, dass der httpclient und einige andere populäre Klassen veraltet waren und ich kann kein richtiges Tutorial finden, um mich zu diesem Thema zu unterrichten. Jede Hilfe wird geschätzt.Senden und empfangen json obj in Android

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: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="deardanielxd.travain2.MainActivity"> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:textAppearance="?android:attr/textAppearanceSmall" 
    android:text="Username : " 
    android:id="@+id/Username_Lbl" 
    android:layout_alignParentTop="true" 
    android:layout_alignParentStart="true" 
    android:editable="true" 
    android:minHeight="20dp" 
    android:layout_alignBottom="@+id/Username_Field" 
    android:layout_toStartOf="@+id/Username_Field" 
    android:layout_alignEnd="@+id/Password_Lbl" /> 

<EditText 
    android:layout_width="wrap_content" 
    android:layout_height = "40dp" 
    android:textAppearance="?android:attr/textAppearanceSmall" 
    android:id="@+id/Username_Field" 
    android:editable="true" 
    android:contextClickable="true" 
    android:textIsSelectable="true" 
    android:enabled="true" 
    android:focusable="true" 
    android:clickable="true" 
    android:inputType="text" 
    android:minHeight="40dp" 
    android:layout_alignParentTop="true" 
    android:layout_alignEnd="@+id/Load_Btn" 
    android:layout_toEndOf="@+id/Password_Lbl" /> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:textAppearance="?android:attr/textAppearanceSmall" 
    android:text="Password : " 
    android:id="@+id/Password_Lbl" 
    android:layout_below="@+id/Username_Lbl" 
    android:layout_alignParentStart="true" 
    android:minHeight="20dp" 
    android:layout_alignBottom="@+id/Password_Field" /> 

<EditText 
    android:layout_width="wrap_content" 
    android:layout_height="40dp" 
    android:textAppearance="?android:attr/textAppearanceSmall" 
    android:id="@+id/Password_Field" 
    android:password="true" 
    android:editable="true" 
    android:textIsSelectable="true" 
    android:enabled="true" 
    android:focusable="true" 
    android:contextClickable="true" 
    android:clickable="true" 
    android:inputType="text" 
    android:minHeight="40dp" 
    android:layout_below="@+id/Username_Field" 
    android:layout_alignParentEnd="true" 
    android:layout_alignStart="@+id/Username_Field" /> 

<Button 
    style="?android:attr/buttonStyleSmall" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Load" 
    android:id="@+id/Load_Btn" 
    android:layout_alignParentEnd="true" 
    android:layout_alignBottom="@+id/spinner" 
    android:layout_below="@+id/Password_Field" /> 

<Spinner 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/spinner" 
    android:spinnerMode="dropdown" 
    android:layout_alignParentStart="true" 
    android:layout_toStartOf="@+id/Load_Btn" 
    android:layout_below="@+id/Password_Lbl" /> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/SysMsg" 
    android:layout_alignParentStart="true" 
    android:layout_alignParentBottom="true" 
    android:layout_alignParentEnd="true" 
    android:text="System : " 
    android:textColor="#FF0000" /> 

<ScrollView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/scrollView" 
    android:layout_below="@+id/spinner" 
    android:layout_alignParentStart="true" 
    android:layout_above="@+id/SysMsg" 
    android:layout_alignParentEnd="true" > 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/OutPut" 
     android:enabled="true" /> 
</ScrollView> 

MainActivity.java

package deardanielxd.travain2; 

import android.content.Context; 
import android.net.ConnectivityManager; 
import android.net.NetworkInfo; 
import android.os.AsyncTask; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.widget.AdapterView; 
import android.widget.ArrayAdapter; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.Spinner; 
import android.widget.TextView; 
import org.json.JSONObject; 
import java.io.BufferedInputStream; 
import java.io.BufferedReader; 
import java.io.DataOutputStream; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.OutputStream; 
import java.net.HttpURLConnection; 
import java.net.URL; 
import java.net.URLEncoder; 


public class MainActivity extends AppCompatActivity { 

    Spinner spinner; 
    EditText Username, Password; 
    Button Load_Btn; 
    TextView Main_Output; 
    TextView Sys_Output; 
    String server = ""; 
    boolean debug = true; 
    PlayerInfo curr = new PlayerInfo(); 

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

     SetupGadget(); 
     attachListener(); 

    } 

    private void SetupGadget() { 
     spinner = (Spinner) findViewById(R.id.spinner); 
     Username = (EditText) findViewById(R.id.Username_Field); 
     Password = (EditText) findViewById(R.id.Password_Field); 
     Load_Btn = (Button) findViewById(R.id.Load_Btn); 
     Main_Output = (TextView) findViewById(R.id.OutPut); 
     Sys_Output = (TextView) findViewById(R.id.SysMsg); 

     ArrayAdapter adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,Constants.Servers); 
     spinner.setAdapter(adapter); 
    } 

    private void attachListener() { 
     Load_Btn.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       if (debug) { 
        MainOutput("Username : " + Username.getText()); 
        MainOutput("Password : " + Password.getText()); 
        MainOutput("Server : " + server); 
        MainOutput("Internet Connection : " + (InternetAccess()?"Yes":"No")); 
        MainOutput(""); 
       } 

       new test(MainActivity.this).execute(); 

      } 
     }); 

     spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 
      @Override 
      public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { 
       server = parent.getSelectedItem().toString(); 
      } 

      @Override 
      public void onNothingSelected(AdapterView<?> parent) { 

      } 
     }); 

    } 

    private void SystemOutput(String output) { 
     Sys_Output.setText("System : " + output); 
    } 

    public void MainOutput(String output) { 
     Main_Output.append("\n" + output); 
    } 

    private boolean InternetAccess() { 
     ConnectivityManager cm = 
       (ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE); 

     NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); 
     return activeNetwork != null && 
       activeNetwork.isConnectedOrConnecting(); 

    } 

    public class test extends AsyncTask<Void, Void, Void> 

    { 
     private MainActivity MA; 

     test(MainActivity ma) { 
      MA = ma; 
     } 

     @Override 
     protected Void doInBackground(Void... n) { 

      try { 
       URL url = new URL("http://"+MA.server+"/api/external.php"); 
       HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 

       urlConnection.setDoOutput(true); 
       urlConnection.setRequestProperty("Content-Type","application/json"); 
       urlConnection.setRequestProperty("Host", "android.schoolportal.gr"); 
       urlConnection.setRequestMethod("POST"); 
       urlConnection.setUseCaches(false); 
       urlConnection.connect(); 

       OutputStream printout = new DataOutputStream(urlConnection.getOutputStream()); 
       printout.write(URLEncoder.encode(this.getObj().toString(),"UTF-8").getBytes()); 
       printout.flush(); 
       printout.close(); 

       try { 
        urlConnection.setRequestMethod("GET"); 
        urlConnection.setDoInput(true); 
        InputStream in = new BufferedInputStream(urlConnection.getInputStream()); 
        BufferedReader r = new BufferedReader(new InputStreamReader(in)); 
        StringBuilder total = new StringBuilder(in.available()); 
        String line; 
        while ((line = r.readLine()) != null) { 
         total.append(line).append('\n'); 
        } 
        MA.MainOutput(total.toString()); 
        MA.MainOutput("End of Doc"); 
       } finally { 
        urlConnection.disconnect(); 
        return null; 
       } 
      } catch (java.net.MalformedURLException e) { 

      } catch (java.io.IOException e) { 

      }; 
      return null; 

     } 

     private JSONObject getObj() { 

      JSONObject jobj = new JSONObject(); 
      try { 
       jobj.put("email","[email protected]"); 
       jobj.put("siteName","EasyTravian"); 
       jobj.put("sitUrl","testing.com"); 
       jobj.put("public",false); 
      } catch (org.json.JSONException e) { 

      } 
      return jobj; 

     } 

    } 

    public PlayerInfo getCurrentPlayerInfo() { 
     return this.curr; 
    } 

    public void UpdateCurr() { 
     this.curr.Username = this.Username.getText().toString(); 
     this.curr.Password = this.Password.getText().toString(); 
     this.curr.Server = this.server; 
    } 

    } 

Constants.java

public class Constants { 
public static final String[] Servers = { 
    "ts1.travian.hk", 
    "ts2.travian.hk", 
    "ts20.travian.hk", 
    "tx3.travian.hk", 
    "ts4.travian.hk", 
    "ts19.travian.hk", 
    "ts3.travian.hk", 
    "ts6.travian.hk", 
    "ts5.travian.hk" 
}; 

} 
+0

Mate Blick in Volley, wird Ihr Leben einfacher hier – Memme

+0

Versuchen [Retrofit] (http: //square.github.I/Retrofit /) –

Antwort

0

Verwenden Volley ist es Geschwindigkeit & bester Weg.
Fügen Sie die folgenden lib in Ihrem build.gradle Datei
Volley tutorial

0

Sie sollten verwenden Volley-Bibliothek für sie

compile 'com.android.volley:volley:1.0.0' 

Dieses Video finden. Es ist sehr gut für die Rest API's.

Und Verwalten von Serveraufrufen ist damit einfach.

die Bibliothek hinzufügen von

compile 'com.android.volley:volley:1.0.0' 

dann eine Singleton-Klasse machen Kompilieren alle Volley Anfragen zu bearbeiten.

Volley bietet JsonArrayRequest und JsonObjectRequest, die während Netzwerkaufrufen sehr hilfreich sind.

Hier Volley Singletonklasse

public class MyApplication extends Application 
{ 

    private RequestQueue mRequestQueue; 
    private static MyApplication mInstance; 

    @Override 
    public void onCreate() 
    { 
     super.onCreate(); 
     mInstance = this; 
    } 

    public static synchronized MyApplication getInstance() 
    { 
     return mInstance; 
    } 

    public RequestQueue getReqQueue() 
    { 
     if (mRequestQueue == null) 
     { 
      mRequestQueue = Volley.newRequestQueue(getApplicationContext()); 
     } 

     return mRequestQueue; 
    } 

    public <T> void addToReqQueue(Request<T> req, String tag) 
    { 

     getReqQueue().add(req); 
    } 

    public <T> void addToReqQueue(Request<T> req) 
    { 

     getReqQueue().add(req); 
    } 

    public void cancelPendingReq(Object tag) 
    { 
     if (mRequestQueue != null) { 
      mRequestQueue.cancelAll(tag); 
     } 
    } 
} 

Fügen Sie diese auf Ihre Anwendung Tag in manifest

<application 
android:name="MyApplication"> 

Dies ist ein Beispiel JsonObjectRequest

JsonObjectRequest request = new JsonObjectRequest("requestMethod","url","input_data", 
         new Response.Listener<JSONObject>() 
         { 
          @Override 
          public void onResponse(JSONObject response) 
          { 
          } 
         }, 
         new Response.ErrorListener() 
         { 
          @Override 
          public void onErrorResponse(VolleyError error) 
          { 
          } 
         }); 
       MyApplication.getInstance().addToReqQueue(request); 
0

Ich glaube nicht, Sie ist, sollte kodiere den Text der Nachricht. Der Grund, dass es "URLEncoder" heißt, ist, weil es verwendet wird, um eine URL zu verschlüsseln, aber das ist der Körper Ihrer Nachricht.

Auch der interne try Block, den Sie haben, ist redundant und Sie sollten auch die Request-Methode zu GET in der Mitte der Anfrage ändern.

Die Bytes müssen nicht gelöscht werden.

Denken Sie daran, dass bei einer POST-Anfrage nichts gesendet wird, bis Sie die Antwort mit Ihrem InputStream gelesen haben.

Verwandte Themen