0

我有一个 API 团队要求我格式化来自我们的 android 应用程序的搜索请求,如下所示:

Method: GET
Headers:
{
    "Content-Type": "application/json",
    "X-AUTHORIZATION": "8eb40dba2f0c6d7de8b9c6e1865aa507"
}
Request:
{
    "keyword": "daft"
}
Response:
{
    "status": "success",
    "code": 0,
    "meta": {
        "exec_time": 0.014711856842041
    },
    "message": "",
    "data": [

    ]
}

我已经工作了很长时间,现在可能会发疯,但是甚至可以发出 GET 请求并发布 JSON 吗?我认为HttpGet不允许setEntity()

这是代表此类调用的方法:

public HttpResponse invokeXAUTHGETJsonService(String url, String token,
            String jsonPost) {

        client = new DefaultHttpClient();

        HttpResponse response = null;

        try {
            HttpGet request = new HttpGet(url);
            Log.v("UPU", "URL:" + url +" token:"+token);

            request.addHeader("X-AUTHORIZATION", token);
            request.addHeader("Content-Type", "application/json");

            StringEntity se = new StringEntity(jsonPost);
            //request.setEntity(se) // WAIT NOT POSSIBLE RIGHT?

            response = client.execute(request);
        } catch (ClientProtocolException e) {

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

            e.printStackTrace();
        }
        return response;

    }
4

1 回答 1

0

这是获取 JSON 数据的工作示例

我使用了 Android 异步 Http 客户端库。如果您不使用https则可以忽略 client.setSSLSocketFactory(getSSLSocketFactory());.

类 RestTest

import org.json.JSONArray;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams; 

public class  RestTest {

private static void getDataFromRest(){
    RequestParams params = new RequestParams();
    params.add("X-API-KEY", YOUR_REST_X_API_KEY);
    RestClient.put(YOUR_REST_METHOD_URL, params, new JsonHttpResponseHandler(){
        @Override
        public void onSuccess(JSONArray response) {
            System.out.println(response);
        }
    });
}
}

类 RestClent

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.conn.ssl.SSLSocketFactory;

public class RestClient {

private static final String BASE_URL = "https://YOUR_DOMAIN.COM/";

private static AsyncHttpClient client = new AsyncHttpClient();

public static void get(String url, RequestParams params,
        AsyncHttpResponseHandler responseHandler) {
    client.setSSLSocketFactory(getSSLSocketFactory());
    client.get(getAbsoluteUrl(url), params, responseHandler);
}

public static void post(String url, RequestParams params,
        AsyncHttpResponseHandler responseHandler) {
    client.setSSLSocketFactory(getSSLSocketFactory());
    client.post(getAbsoluteUrl(url), params, responseHandler);
}

public static void put(String url, RequestParams params,
        AsyncHttpResponseHandler responseHandler) {
    client.setSSLSocketFactory(getSSLSocketFactory());
    client.put(getAbsoluteUrl(url), params, responseHandler);
}

private static String getAbsoluteUrl(String relativeUrl) {
    return BASE_URL + relativeUrl;
}

public static class VoipemSSLSocketFactory extends SSLSocketFactory {
    SSLContext sslContext = SSLContext.getInstance("TLS");

    public VoipemSSLSocketFactory(KeyStore truststore)
            throws NoSuchAlgorithmException, KeyManagementException,
            KeyStoreException, UnrecoverableKeyException {
        super(truststore);

        TrustManager tm = new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] chain,
                    String authType) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] chain,
                    String authType) throws CertificateException {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        sslContext.init(null, new TrustManager[] { tm }, null);
    }

    @Override
    public Socket createSocket(Socket socket, String host, int port,
            boolean autoClose) throws IOException, UnknownHostException {
        return sslContext.getSocketFactory().createSocket(socket, host,
                port, autoClose);
    }

    @Override
    public Socket createSocket() throws IOException {
        return sslContext.getSocketFactory().createSocket();
    }
}

private static SSLSocketFactory getSSLSocketFactory() {
    KeyStore trustStore;
    SSLSocketFactory sslSocketFactory = null;
    try {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        sslSocketFactory = new VoipemSSLSocketFactory(trustStore);
        sslSocketFactory
                .setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); 
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) { 
    }
    return sslSocketFactory;
}
}
于 2014-03-08T20:02:23.027 回答