使用okhttp将数据发布到服务器

时间:2015-08-31 09:14:24

标签: java android okhttp

如何使用okhttp将数据从我的Android应用程序发布到php服务器?它甚至可能吗?我已经能够从服务器检索数据,但我需要将String从我的应用程序发送到服务器。

感谢。

OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder().url(requestUrl).build();
    Call call = client.newCall(request);
    try {
        Response response = call.execute();
        if(response.isSuccessful()){
            Log.v("LOGV", response.body().string());
        }
    } catch (IOException e) {
        e.printStackTrace();
        Log.v("LOGV", e.getMessage().toString());
    }

1 个答案:

答案 0 :(得分:1)

以下是okhttp网站的示例:

public static final MediaType JSON
    = MediaType.parse("application/json; charset=utf-8"); //defines the type of the body 

OkHttpClient client = new OkHttpClient();

String post(String url, String json) throws IOException {
  RequestBody body = RequestBody.create(JSON, json);
  Request request = new Request.Builder()
      .url(url)
      .post(body) //include the body in the request with the POST method
      .build();
  Response response = client.newCall(request).execute();
  return response.body().string();
}

带有类似示例的github回购链接:https://raw.githubusercontent.com/square/okhttp/master/samples/guide/src/main/java/com/squareup/okhttp/guide/PostExample.java