Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/191.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Android中使用Gson向服务器发送带有参数的Get和Post请求_Android_Web Services_Gson - Fatal编程技术网

如何在Android中使用Gson向服务器发送带有参数的Get和Post请求

如何在Android中使用Gson向服务器发送带有参数的Get和Post请求,android,web-services,gson,Android,Web Services,Gson,我是android开发新手。我正在从事一个rest API web服务基础项目。我想向服务器发送带有参数的请求以获得响应,但不知道如何做。 我需要有关示例的帮助。使用。 它有Gson支持 您可以参考下面的一些示例/教程 一, 2.尝试对非标准JSON格式使用Okhttp。 格雷德尔要求: compile 'com.squareup.okhttp:okhttp:2.4.0' compile 'com.squareup.okio:okio:1.6.0' public static final M

我是android开发新手。我正在从事一个rest API web服务基础项目。我想向服务器发送带有参数的请求以获得响应,但不知道如何做。 我需要有关示例的帮助。

使用。 它有Gson支持

您可以参考下面的一些示例/教程

一,


2.

尝试对非标准JSON格式使用Okhttp。 格雷德尔要求:

compile 'com.squareup.okhttp:okhttp:2.4.0'
compile 'com.squareup.okio:okio:1.6.0'

 public static final MediaType JSON = MediaType
        .parse("application/json; charset=utf-8");

public static String getJSONResponseFromOkhttp(OkHttpClient okHttpClient, String url) {

    Request request = new Request.Builder().url(url).build();
//If require login in header.(O-Auth). Else don't use it.
    okHttpClient.setAuthenticator(new Authenticator() {
        @Override
        public Request authenticate(Proxy proxy, Response response) throws IOException {
            String credential = Credentials.basic("admin", "password@123");
            return response.request().newBuilder().header("Authorization", credential).build();
        }

        @Override
        public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
            return null;
        }
    });

    String jsonresponse = null;
    try {
        okHttpClient.setConnectTimeout(0, TimeUnit.SECONDS); // connect timeout
        okHttpClient.setReadTimeout(0, TimeUnit.SECONDS);

        Response response = okHttpClient.newCall(request).execute();
        jsonresponse = response.body().string();
//            Log.e("community response.", jsonresponse);
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (jsonresponse != null) {
        Log.e("community response.", jsonresponse);

    }
    return jsonresponse;
}
我如何使用它……:

response = OkHttpClass.getJSONResponseFromOkhttp(new OkHttpClient(), mUrl);
因为改型使用GSON转换器,它将只接受标准JSON响应格式。在改型中,您不必解析JSON响应。它们由GSON库自动解析并保存到模型POJO

有关改装,请参阅此。