connect to RESTful api

邮差的信 提交于 2021-02-11 12:17:54

问题


i need help to connect to this api this is Documentation: http://www.jazzradio.fr/api-docs

the website example is in php and i not understand

i have public-key and private-key

please help me to connect i tried

url = "http://www.jazzradio.fr/api/news"
List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("limit", "20"));
            params.add(new BasicNameValuePair("private_key ", "***"));
            JSONObject json = jParser.makeHttpRequest(url, "GET", params);

is that true


回答1:


Old school is like this: (nothing wrong with Volley)

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;

    try {
        // The following SSL code is temporary and allows access to the IIS Server that has a self-signed certificate

        // Setup a custom SSL Factory object which simply ignore the certificates
        // validation and accept all type of self signed certificates
        SSLSocketFactory sslFactory = new SimpleSSLSocketFactory(null);
        sslFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        // Enable HTTP parameters
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        // Register the HTTP and HTTPS Protocols. For HTTPS, register our custom SSL Factory object.
        SchemeRegistry registry = new SchemeRegistry();

        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sslFactory, 443));

        // Create a new connection manager using the newly created registry and then create a new HTTP client
        // using this connection manager
        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
        DefaultHttpClient httpClient = new DefaultHttpClient(ccm, params);
        HttpGet request = new HttpGet();

        URI uri = new URI(resources.getString("http://www.jazzradio.fr/api-docs"));
        request.setURI(uri);
        HttpResponse response = httpClient.execute(request);


        if (response.getStatusLine().toString().equalsIgnoreCase(HTTP_STATUS_OK)) {
            isRestfulServiceAvailable = true;

            bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            // JSON data is in bufferedReader
            // Get from bufferedReader to JSONArray, then from JSONArray to ArrayList

            String line = bufferedReader.readLine();
            stringBuilder.append(line);

            ...



回答2:


Using volley:

In MainActivity.java, in OnCreate(), OnStart(), or OnResume() depending on the application:

private void getClientResource() {
       final RequestQueue  mRequestQueue = Volley.newRequestQueue(this);

       Resources resources = getResources();
       URL url = null;
       try {
           url = new URL(resources.getString(R.string.your_url_here));
       }
       catch (MalformedURLException e) {
           e.printStackTrace();
       }
       final String urlString = url.toString();

       final Response.Listener<JSONObject> responseListener = new Response.Listener<JSONObject>() {

           @Override
           public void onResponse(JSONObject response) {
               VolleyLog.v("Response: %s", response.toString());
               // parse JSON response here
           }
       };

       final Response.ErrorListener errorListener = new Response.ErrorListener() {
               @Override
               public void onErrorResponse(VolleyError error) {
                   VolleyLog.e("Error.Response: %s", error.toString());
                   Log.e("Error.Response: %s", error.toString());
                   if(error instanceof NoConnectionError) {
                       Toast.makeText(mActivity, "No internet available", Toast.LENGTH_SHORT).show();
                   }
                   else if(error instanceof ServerError) {
                       Toast.makeText(mActivity, "Invalid username/password", Toast.LENGTH_SHORT).show();
                   }
                   else if(error instanceof AuthFailureError) {
                       Toast.makeText(mActivity, "AuthFailureError", Toast.LENGTH_SHORT).show();
                   }
                   else if(error instanceof NetworkError) {
                       Toast.makeText(mActivity, "NetworkError", Toast.LENGTH_SHORT).show();
                   }
                   else if(error instanceof ParseError) { 
                       Toast.makeText(mActivity, "ParseError: ", Toast.LENGTH_SHORT).show();
                   }
                   else if(error instanceof VolleyError) {
                       Toast.makeText(mActivity, "VolleyError", Toast.LENGTH_SHORT).show();
                   }
                   else if(error instanceof TimeoutError) {
                       Toast.makeText(mActivity, "TimeoutError", Toast.LENGTH_SHORT).show();
                   }
                   else {
                       Toast.makeText(mActivity, "Error: " + error, Toast.LENGTH_SHORT).show();
                   }
               }
           };

           TaskJsonObjectRequest jsObjRequest = new TaskJsonObjectRequest(Request.Method.GET,
               urlString,
               null,
               responseListener,
               errorListener);

       mRequestQueue.add(jsObjRequest);
}

TaskJsonObjectRequest.java

import android.util.Base64;

import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.toolbox.JsonObjectRequest;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class TaskJsonObjectRequest extends JsonObjectRequest {

    public TaskJsonObjectRequest(int requestMethod,
                                 String url,
                                 JSONObject jsonRequest,
                                 Response.Listener<JSONObject> listener,
                                 Response.ErrorListener errorListener) {
        super(requestMethod,
                url, //String url,
                jsonRequest, // JSONObject ,
                listener, // Response.Listener<JSONObject> ,
                errorListener); // Response.ErrorListener errorListener)
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> headers = new HashMap<String, String>();
        String auth = "Basic " + Base64.encodeToString(("yi_z:secret").getBytes(), Base64.NO_WRAP);
        headers.put("Authorization", auth);
        return headers;

    }
}


来源:https://stackoverflow.com/questions/32507758/connect-to-restful-api

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!