2016-05-03 10 views
0

Ich möchte Verbindung mit der API und die Zeichenfolge Daten an die API, um die JSON-Ergebnis zu erhalten, aber ich weiß nicht, wie es hier gemacht wird, ist meine code, kann jemand mir sagen, wie man json Daten in diese URL Verbindung setzen und eswie JSON-Daten auf die restful API im Header zu json Antwort android senden

package practise.c.practise; 

    import android.os.Handler; 
    import android.os.Message; 
    import android.support.v7.app.AppCompatActivity; 
    import android.os.Bundle; 
    import android.util.Base64; 
    import android.util.Log; 
    import android.widget.Toast; 

    import java.io.BufferedReader; 
    import java.io.IOException; 
    import java.io.InputStream; 
    import java.io.InputStreamReader; 
    import java.net.HttpURLConnection; 
    import java.net.MalformedURLException; 
    import java.net.URL; 

    public class API extends AppCompatActivity { 
     String USERID; 
     String APIKEY; 


     @Override 
     protected void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.activity_api); 
      Log.d("oncreate", "onCreate: "); 

      Thread thread = new Thread(new Runnable() { 
       @Override 
       public void run() { 

        try { 
         Log.d("threadrun", "onCreate: "); 
         URL url = new URL("https://api.api.com/v1"); 
         HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection(); 
         String userCredentials = "2223:6c005hhhh1eggggf4447b59bfed"; 
         String basicAuth = Base64.encodeToString(userCredentials.getBytes(),Base64.DEFAULT); 
         httpURLConnection.setRequestProperty ("Authorization","Basic" + basicAuth); 
         httpURLConnection.setRequestMethod("POST"); 
         httpURLConnection.setRequestProperty("Accept-Language", "en"); 
         int responseCode = httpURLConnection.getResponseCode(); 

         Log.d("responsecode", "run: "+responseCode); 

         if(responseCode == 200){ 

          InputStream inputStr = httpURLConnection.getInputStream(); 
          BufferedReader reader = new BufferedReader(new InputStreamReader(inputStr)); 
          StringBuilder result = new StringBuilder(); 
          String line; 
          while((line = reader.readLine()) != null) { 
           result.append(line); 
          } 
          Log.d("API:DATA", "run: "+result); 

         } 



        } catch (Exception e) { 
         e.printStackTrace(); 
        } 

       } 
      }); 
      thread.start(); 





     } 




    } 

Antwort

1

Versuchen Sie die folgende Code-Vorlage. Was Sie brauchen, wird in den Kommentaren im Code erläutert.

/** 
* Created by sibidharan on 18/11/14. 
* Sample class 
*/ 

import android.graphics.Bitmap; 
import android.net.Uri; 
import android.os.Build; 
import android.util.Log; 

import org.apache.http.entity.mime.HttpMultipartMode; 
import org.apache.http.entity.mime.content.ByteArrayBody; 
import org.apache.http.entity.mime.content.ContentBody; 
import org.apache.http.entity.mime.content.StringBody; 
import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import java.io.BufferedReader; 
import java.io.BufferedWriter; 
import java.io.ByteArrayOutputStream; 
import java.io.FileNotFoundException; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.OutputStream; 
import java.io.OutputStreamWriter; 
import java.net.HttpURLConnection; 
import java.net.SocketTimeoutException; 
import java.net.URL; 
import java.net.UnknownHostException; 

import javax.net.ssl.HttpsURLConnection; 
import javax.net.ssl.SSLPeerUnverifiedException; 

/* 
Usage of the class 

Create all the necessary API Call methods you need. 
And either use a Thread or AsyncTask to call the following. 

    JSONObject response = ApiUrlCalls.login("username", "passowrd"); 

After the response is obtained, check for status code like 

    if(response.getInt("status_code") == 200){ 
     //TODO: code something 
    } else { 
     //TODO: code something 
    } 
*/ 

public class ApiUrlCalls { 

    private String HOST = "https://domain/path/"; //This will be concated with the function needed. Ref:1 

    /* 
     Now utilizing the method is so simple. Lets consider a login function, which sends username and password. 
     See below for example. 
    */ 

    public static JSONObject login(String username, String password){ 

     String functionCall = "login"; 
     Uri.Builder builder = new Uri.Builder() 
       .appendQueryParameter("username", username) 
       .appendQueryParameter("password", password); 

     /* 
      The return calls the apiPost method for processing. 
      Make sure this should't happen in the UI thread, orelse, NetworkOnMainThread exception will be thrown. 
     */ 
     return apiPost(builder, functionCall); 

    } 

    /* 
     This method is the one which performs POST operation. If you need GET, just change it 
     in like Connection.setRequestMethod("GET") 
    */ 
    private static JSONObject apiPost(Uri.Builder builder, String function){ 
     try { 
      int TIMEOUT = 15000; 
      JSONObject jsonObject = new JSONObject(); 
      try { 
       URL url = null; 
       String response = ""; 

       /* 
        Ref:1 
        As mentioned, here below, in case the function is "login", 
        url looks like https://domain/path/login 

        This is generally a rewrited form by .htaccess in server. 
        If you need knowledge on RESTful API in PHP, refer 
        http://stackoverflow.com/questions/34997738/creating-restful-api-what-kind-of-headers-should-be-put-out-before-the-response/35000332#35000332 

        I have answered how to create a RESTful API. It matches the above URL format, it also includes the .htaccess 
       */ 

       url = new URL(HOST + function); 

       HttpsURLConnection conn = null; 
       conn = (HttpsURLConnection) url.openConnection(); 
       assert conn != null; 
       conn.setReadTimeout(TIMEOUT); 
       conn.setConnectTimeout(TIMEOUT); 
       conn.setRequestMethod("POST"); 
       conn.setDoInput(true); 
       conn.setDoOutput(true); 

       String query = builder.build().getEncodedQuery(); 

       OutputStream os = conn.getOutputStream(); 
       BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); 
       writer.write(query); 
       writer.flush(); 
       writer.close(); 
       os.close(); 
       conn.connect(); 


       int responseCode = conn.getResponseCode(); 
       String responseMessage = conn.getResponseMessage(); 
       jsonObject.put("status_code", responseCode); 
       jsonObject.put("status_message", responseMessage); 

       /*The if condition below will check if status code is greater than 400 and sets error status 
       even before trying to read content, because HttpUrlConnection classes will throw exceptions 
       for status codes 4xx and 5xx. You cannot read content for status codes 4xx and 5xx in HttpUrlConnection 
       classes. 
       */ 

       if (jsonObject.getInt("status_code") >= 400) { 
        jsonObject.put("status", "Error"); 
        jsonObject.put("msg", "Something is not good. Try again later."); 
        return jsonObject; 
       } 

       String line; 
       BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); 

       while ((line = br.readLine()) != null) { 
        response += line; 
       } 
       //Log.d("RESP", response); 

       /* 
        After the actual payload is read as a string, it is time to change it into JSON. 
        Simply when it starts with "[" it should be a JSON array and when it starts with "{" 
        it is a JSONObject. That is what hapenning below. 
       */ 
       if(response.startsWith("[")) { 
        jsonObject.put("content", new JSONArray(response)); 
       } 
       if(response.startsWith("{")){ 
        jsonObject.put("content", new JSONObject(response)); 
       } 


      } catch(UnknownHostException e) { 
      //No explanation needed :) 
       jsonObject.put("status", "UnknownHostException"); 
       jsonObject.put("msg", "Check your internet connection"); 
      } catch (SocketTimeoutException){ 
      //This is when the connection timeouts. Timeouts can be modified by TIMEOUT variable above. 
       jsonObject.put("status", "Timeout"); 
       jsonObject.put("msg", "Check your internet connection"); 
      } catch (SSLPeerUnverifiedException se) { 
      //When an untrusted SSL Certificate is received, this happens. (Only for https.) 
       jsonObject.put("status", "SSLException"); 
       jsonObject.put("msg", "Unable to establish secure connection."); 
       se.printStackTrace(); 
      } catch (IOException e) { 
      //This generally happens when there is a trouble in connection 
       jsonObject.put("status", "IOException"); 
       jsonObject.put("msg", "Check your internet connection"); 
       e.printStackTrace(); 
      } catch(FileNotFoundException e){ 
      //There is no chance that this catch block will execute as we already checked for 4xx errors 
       jsonObject.put("status", "FileNotFoundException"); 
       jsonObject.put("msg", "Some 4xx Error"); 
       e.printStackTrace(); 
      } catch (JSONException e){ 
      //This happens when there is a troble reading the content, or some notice or warnings in content, 
      //which generally happens while we modify the server side files. Read the "msg", and it is clear now :) 
       jsonObject.put("status", "JSONException"); 
       jsonObject.put("msg", "We are experiencing a glitch, try back in sometime."); 
       e.printStackTrace(); 
      } return jsonObject; 

     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
     return null; 
    } 

} 
+0

können Sie mir sagen, was ich tun soll in meinem Code und wie sollte ich Daten in meinem Code übergeben, ist Ihre Lösung gut, aber als .. ich werde um die Logik meines Codes zu ändern .. ist mein Code falsch? – bipin

+0

Ihr Code sieht gut aus, aber die API-Ebene wurde von 'AppCompactActivity' erweitert, was nicht empfohlen wird. Erstellen Sie einfach eine Methode, wie ich sie im obigen Code erklärt habe, und der Rest wird automatisch erledigt, da ich die Funktion dort geschrieben habe. Wie die Beispiel-Login-Funktion, lassen Sie meine Methode wissen, was sie zu posten hat. Rufen Sie die Methode apiPost von der statischen Methode auf. Einfach. Lesen Sie den Code zweimal, um die Idee zu bekommen. – Sibidharan

+0

'Uri.Builder' enthält die zu sendenden Formulardaten [POST/GET]. Addiere so viel wie du willst und sende es dann an 'apiPost()' method mit der 'function' string welche die' http: // example.com/api/function' oder wie es sein muss. Es wird angehängt mit dem Host, und weiterverarbeitet, und gibt Ihnen die resultierende JSON. Es ist so einfach wie einen Kuchen zu essen. – Sibidharan

0

ich nur Änderungen in zwei Linien von meinem Code und mein Code zu arbeiten begann

URL url = new URL (“http://api.api.com/v1 "); // http statt https httpURLConnection.setRequestProperty (" Authorization "," Basic "+ basicAuth); // gab Platz nach Basic