如何使用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());
}
答案 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