简体   繁体   English

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

[英]Post data to server with okhttp

How can I post data from my android app to php server with okhttp?如何使用 okhttp 将数据从我的 android 应用程序发布到 php 服务器? Is it even possible?甚至有可能吗? I've been able to retrieve data from the server, but I need to send String from my application to the server.我已经能够从服务器检索数据,但是我需要将 String 从我的应用程序发送到服务器。

Thanks.谢谢。

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());
    }

Here is example from okhttp website:以下是 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();
}

And a link to their github repo with similar example: https://raw.githubusercontent.com/square/okhttp/master/samples/guide/src/main/java/com/squareup/okhttp/guide/PostExample.java以及指向他们 github 存储库的链接,其中包含类似示例: https : //raw.githubusercontent.com/square/okhttp/master/samples/guide/src/main/java/com/squareup/okhttp/guide/PostExample.java

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM