如何在Android中使用okhttp库向api(http post)添加参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24233632/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add parameters to api (http post) using okhttp library in Android
提问by M.A.Murali
In my Android application, I am using okHttplibrary. How can I send parameters to the server(api) using the okhttp library? currently I am using the following code to access the server now need to use the okhttp library.
在我的 Android 应用程序中,我使用的是okHttp库。如何使用 okhttp 库向服务器(api)发送参数?目前我正在使用以下代码访问服务器,现在需要使用 okhttp 库。
this is the my code:
这是我的代码:
httpPost = new HttpPost("http://xxx.xxx.xxx.xx/user/login.json");
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("email".trim(), emailID));
nameValuePairs.add(new BasicNameValuePair("password".trim(), passWord));
httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
String response = new DefaultHttpClient().execute(httpPost, new BasicResponseHandler());
回答by Bao Le
For OkHttp 3.x, FormEncodingBuilder was removed, use FormBody.Builder instead
对于 OkHttp 3.x,FormEncodingBuilder 被移除,使用 FormBody.Builder 代替
RequestBody formBody = new FormBody.Builder()
.add("email", "[email protected]")
.add("tel", "90301171XX")
.build();
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.post(formBody)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
回答by Gennady Kozlov
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
RequestBody formBody = new FormEncodingBuilder()
.add("email", "[email protected]")
.add("tel", "90301171XX")
.build();
Request request = new Request.Builder()
.url("https://en.wikipedia.org/w/index.php")
.post(formBody)
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
回答by matiash
You just need to format the body of the POST before creating the RequestBody
object.
您只需要在创建RequestBody
对象之前格式化 POST 的正文。
You could do this manually, but I'd suggest you use the MimeCraftlibrary from Square (makers of OkHttp).
您可以手动执行此操作,但我建议您使用Square(OkHttp 的制造商)的MimeCraft库。
In this case you'd need the FormEncoding.Builder
class; set the contentType
to "application/x-www-form-urlencoded"
and use add(name, value)
for each key-value pair.
在这种情况下,您需要该FormEncoding.Builder
课程;为每个键值对设置contentType
to"application/x-www-form-urlencoded"
和 use add(name, value)
。
回答by Sufian
None of the answers worked for me, so I played around and below one worked fine. Sharing just in case someone gets stuck with the same issue:
没有一个答案对我有用,所以我四处玩,下面一个工作得很好。分享以防万一有人遇到同样的问题:
Imports:
进口:
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
Code:
代码:
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = new MultipartBuilder()
.type(MultipartBuilder.FORM) //this is what I say in my POSTman (Chrome plugin)
.addFormDataPart("name", "test")
.addFormDataPart("quality", "240p")
.build();
Request request = new Request.Builder()
.url(myUrl)
.post(requestBody)
.build();
try {
Response response = client.newCall(request).execute();
String responseString = response.body().string();
response.body().close();
// do whatever you need to do with responseString
}
catch (Exception e) {
e.printStackTrace();
}
回答by orups
Usually to avoid Exceptions brought about by the code running in UI thread, run the request and response process in a worker thread (Thread or Asynch task) depending on the anticipated length of the process.
通常为了避免运行在 UI 线程中的代码带来的 Exceptions,根据预期的进程长度,在工作线程(线程或异步任务)中运行请求和响应进程。
private void runInBackround(){
new Thread(new Runnable() {
@Override
public void run() {
//method containing process logic.
makeNetworkRequest(reqUrl);
}
}).start();
}
private void makeNetworkRequest(String reqUrl) {
Log.d(TAG, "Booking started: ");
OkHttpClient httpClient = new OkHttpClient();
String responseString = "";
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String booked_at = sdf.format(c.getTime());
try{
RequestBody body = new FormBody.Builder()
.add("place_id", id)
.add("booked_at", booked_at)
.add("booked_by", user_name.getText().toString())
.add("booked_from", lat+"::"+lng)
.add("phone_number", user_phone.getText().toString())
.build();
Request request = new Request.Builder()
.url(reqUrl)
.post(body)
.build();
Response response = httpClient
.newCall(request)
.execute();
responseString = response.body().string();
response.body().close();
Log.d(TAG, "Booking done: " + responseString);
// Response node is JSON Object
JSONObject booked = new JSONObject(responseString);
final String okNo = booked.getJSONArray("added").getJSONObject(0).getString("response");
Log.d(TAG, "Booking made response: " + okNo);
runOnUiThread(new Runnable()
{
public void run()
{
if("OK" == okNo){
//display in short period of time
Toast.makeText(getApplicationContext(), "Booking Successful", Toast.LENGTH_LONG).show();
}else{
//display in short period of time
Toast.makeText(getApplicationContext(), "Booking Not Successful", Toast.LENGTH_LONG).show();
}
}
});
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
}
I hope it helps someone there.
我希望它可以帮助那里的人。
回答by Christian
Another way (without MimeCraft), is to do :
另一种方法(没有 MimeCraft)是:
parameters = "param1=text¶m2=" + param2 // for example !
request = new Request.Builder()
.url(url + path)
.post(RequestBody.create(MEDIA_TYPE_MARKDOWN, parameters))
.build();
and declare :
并声明:
public static final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8");
回答by Aneh Thakur
If you want to send Post data through API using OKHTTP 3 please try below simple code
如果您想使用 OKHTTP 3 通过 API 发送 Post 数据,请尝试以下简单代码
MediaType MEDIA_TYPE = MediaType.parse("application/json");
String url = "https://cakeapi.trinitytuts.com/api/add";
OkHttpClient client = new OkHttpClient();
JSONObject postdata = new JSONObject();
try {
postdata.put("username", "name");
postdata.put("password", "12345");
} catch(JSONException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
RequestBody body = RequestBody.create(MEDIA_TYPE, postdata.toString());
Request request = new Request.Builder()
.url(url)
.post(body)
.header("Accept", "application/json")
.header("Content-Type", "application/json")
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
String mMessage = e.getMessage().toString();
Log.w("failure Response", mMessage);
//call.cancel();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String mMessage = response.body().string();
Log.e(TAG, mMessage);
}
});
You can read the complete tutorial to send data to server using OKHTTP 3 GET and POST request here:- https://trinitytuts.com/get-and-post-request-using-okhttp-in-android-application/
您可以在此处阅读使用 OKHTTP 3 GET 和 POST 请求将数据发送到服务器的完整教程:- https://trinitytuts.com/get-and-post-request-using-okhttp-in-android-application/