如何使用OKHTTP提出要求?

我读了一些发送jsons到服务器的例子。

有人说:

OkHttp是Java提供的HttpUrlConnection接口的实现。 它提供了一个用于编写内容的inputstream,并不知道(或关心)该内容是什么格式。

现在我想用一个名字和密码的参数做一个普通的URL。

这意味着我需要自己编码名称和值对码stream?

目前接受的答案已经过时。 现在如果你想创build一个发布请求并添加参数,你现在应该将MultipartBody.Builder作为Mime Craft使用 。

RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("somParam", "someValue") .build(); request = new Request.Builder() .url(BASE_URL + route) .method("POST", RequestBody.create(null, new byte[0])) .post(requestBody) .build(); 

根据文档 ,OkHttp版本3用FormBodyFormBody.Builder()replace了FormBody ,所以旧的例子将不再工作。

Form和Multipart机构现在被build模。 我们已经用更强大的FormBodyFormBody.Builder组合replace了不透明的FormEncodingBuilder

同样,我们已经将MultipartBuilder升级为MultipartBodyMultipartBody.PartMultipartBody.Builder

所以,如果你使用OkHttp 3.x,请尝试下面的例子:

 OkHttpClient client = new OkHttpClient(); RequestBody formBody = new FormBody.Builder() .add("message", "Your message") .build(); Request request = new Request.Builder() .url("http://www.foo.bar/index.php") .post(formBody) .build(); try { Response response = client.newCall(request).execute(); // Do something with the response. } catch (IOException e) { e.printStackTrace(); } 
 private final OkHttpClient client = new OkHttpClient(); public void run() throws Exception { RequestBody formBody = new FormEncodingBuilder() .add("search", "Jurassic Park") .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()); } 

您需要使用URLEncoder转义string并使用"=""&"连接它们来自己编码。 或者你可以使用Mimecraft的FormEncoder ,它可以给你一个方便的构build器。

 FormEncoding fe = new FormEncoding.Builder() .add("name", "Lorem Ipsum") .add("occupation", "Filler Text") .build(); 

你可以这样做:

  MediaType JSON = MediaType.parse("application/json; charset=utf-8"); RequestBody body = RequestBody.create(JSON, "{"jsonExample":"value"}"); OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(url) .post(body) .addHeader("Authorization", "header value") //Notice this request has header if you don't need to send a header just erase this part .build(); Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { Log.e("HttpService", "onFailure() Request was: " + request); e.printStackTrace(); } @Override public void onResponse(Response r) throws IOException { response = r.body().string(); Log.e("response ", "onResponse(): " + response ); } }); 

你应该检查lynda.com上的教程。 这里是一个如何编码参数,做出HTTP请求,然后parsing对json对象的响应的例子。

 public JSONObject getJSONFromUrl(String str_url, List<NameValuePair> params) { String reply_str = null; BufferedReader reader = null; try { URL url = new URL(str_url); OkHttpClient client = new OkHttpClient(); HttpURLConnection con = client.open(url); con.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream()); writer.write(getEncodedParams(params)); writer.flush(); StringBuilder sb = new StringBuilder(); reader = new BufferedReader(new InputStreamReader(con.getInputStream())); String line; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } reply_str = sb.toString(); } catch (Exception e) { e.printStackTrace(); return null; } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); return null; } } } // try parse the string to a JSON object. There are better ways to parse data. try { jObj = new JSONObject(reply_str); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } return jObj; } //in this case it's NameValuePair, but you can use any container public String getEncodedParams(List<NameValuePair> params) { StringBuilder sb = new StringBuilder(); for (NameValuePair nvp : params) { String key = nvp.getName(); String param_value = nvp.getValue(); String value = null; try { value = URLEncoder.encode(param_value, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } if (sb.length() > 0) { sb.append("&"); } sb.append(key + "=" + value); } return sb.toString(); } 

这是在没有请求主体的情况下实现OKHTTP发布请求的可能解决scheme之一。

 RequestBody reqbody = RequestBody.create(null, new byte[0]); Request.Builder formBody = new Request.Builder().url(url).method("POST",reqbody).header("Content-Length", "0"); clientOk.newCall(formBody.build()).enqueue(OkHttpCallBack()); 

这里是我的方法来做方法地图和数据类似的post请求第一遍

 HashMap<String, String> param = new HashMap<String, String>(); param.put("Name", name); param.put("Email", email); param.put("Password", password); param.put("Img_Name", ""); final JSONObject result = doPostRequest(map,Url); public static JSONObject doPostRequest(HashMap<String, String> data, String url) { try { RequestBody requestBody; MultipartBuilder mBuilder = new MultipartBuilder().type(MultipartBuilder.FORM); if (data != null) { for (String key : data.keySet()) { String value = data.get(key); Utility.printLog("Key Values", key + "-----------------" + value); mBuilder.addFormDataPart(key, value); } } else { mBuilder.addFormDataPart("temp", "temp"); } requestBody = mBuilder.build(); Request request = new Request.Builder() .url(url) .post(requestBody) .build(); OkHttpClient client = new OkHttpClient(); Response response = client.newCall(request).execute(); String responseBody = response.body().string(); Utility.printLog("URL", url); Utility.printLog("Response", responseBody); return new JSONObject(responseBody); } catch (UnknownHostException | UnsupportedEncodingException e) { JSONObject jsonObject=new JSONObject(); try { jsonObject.put("status","false"); jsonObject.put("message",e.getLocalizedMessage()); } catch (JSONException e1) { e1.printStackTrace(); } Log.e(TAG, "Error: " + e.getLocalizedMessage()); } catch (Exception e) { e.printStackTrace(); JSONObject jsonObject=new JSONObject(); try { jsonObject.put("status","false"); jsonObject.put("message",e.getLocalizedMessage()); } catch (JSONException e1) { e1.printStackTrace(); } Log.e(TAG, "Other Error: " + e.getLocalizedMessage()); } return null; } 

  protected Void doInBackground(String... movieIds) { for (; count <= 1; count++) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } Resources res = getResources(); String web_link = res.getString(R.string.website); OkHttpClient client = new OkHttpClient(); RequestBody formBody = new FormBody.Builder() .add("name", name) .add("bsname", bsname) .add("email", email) .add("phone", phone) .add("whatsapp", wapp) .add("location", location) .add("country", country) .add("state", state) .add("city", city) .add("zip", zip) .add("fb", fb) .add("tw", tw) .add("in", in) .add("age", age) .add("gender", gender) .add("image", encodeimg) .add("uid", user_id) .build(); Request request = new Request.Builder() .url(web_link+"edit_profile.php") .post(formBody) .build(); try { Response response = client.newCall(request).execute(); JSONArray array = new JSONArray(response.body().string()); JSONObject object = array.getJSONObject(0); hashMap.put("msg",object.getString("msgtype")); hashMap.put("msg",object.getString("msg")); // Do something with the response. } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return null; } 
  1. 将以下添加到build.gradle

compile 'com.squareup.okhttp3:okhttp:3.7.0'

  1. 创build一个新的线程,在新的线程中添加下面的代码。
 OkHttpClient client = new OkHttpClient(); MediaType MIMEType= MediaType.parse("application/json; charset=utf-8"); RequestBody requestBody = RequestBody.create (MIMEType,"{}"); Request request = new Request.Builder().url(url).post(requestBody).build(); Response response = client.newCall(request).execute(); 
  public static JSONObject doPostRequestWithSingleFile(String url,HashMap<String, String> data, File file,String fileParam) { try { final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png"); RequestBody requestBody; MultipartBuilder mBuilder = new MultipartBuilder().type(MultipartBuilder.FORM); for (String key : data.keySet()) { String value = data.get(key); Utility.printLog("Key Values", key + "-----------------" + value); mBuilder.addFormDataPart(key, value); } if(file!=null) { Log.e("File Name", file.getName() + "==========="); if (file.exists()) { mBuilder.addFormDataPart(fileParam, file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file)); } } requestBody = mBuilder.build(); Request request = new Request.Builder() .url(url) .post(requestBody) .build(); OkHttpClient client = new OkHttpClient(); Response response = client.newCall(request).execute(); String result=response.body().string(); Utility.printLog("Response",result+""); return new JSONObject(result); } catch (UnknownHostException | UnsupportedEncodingException e) { Log.e(TAG, "Error: " + e.getLocalizedMessage()); JSONObject jsonObject=new JSONObject(); try { jsonObject.put("status","false"); jsonObject.put("message",e.getLocalizedMessage()); } catch (JSONException e1) { e1.printStackTrace(); } } catch (Exception e) { Log.e(TAG, "Other Error: " + e.getMessage()); JSONObject jsonObject=new JSONObject(); try { jsonObject.put("status","false"); jsonObject.put("message",e.getLocalizedMessage()); } catch (JSONException e1) { e1.printStackTrace(); } } return null; } public static JSONObject doGetRequest(HashMap<String, String> param,String url) { JSONObject result = null; String response; Set keys = param.keySet(); int count = 0; for (Iterator i = keys.iterator(); i.hasNext(); ) { count++; String key = (String) i.next(); String value = (String) param.get(key); if (count == param.size()) { Log.e("Key",key+""); Log.e("Value",value+""); url += key + "=" + URLEncoder.encode(value); } else { Log.e("Key",key+""); Log.e("Value",value+""); url += key + "=" + URLEncoder.encode(value) + "&"; } } /* try { url= URLEncoder.encode(url, "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); }*/ Log.e("URL", url); OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(url) .build(); Response responseClient = null; try { responseClient = client.newCall(request).execute(); response = responseClient.body().string(); result = new JSONObject(response); Log.e("response", response+"=============="); } catch (Exception e) { JSONObject jsonObject=new JSONObject(); try { jsonObject.put("status","false"); jsonObject.put("message",e.getLocalizedMessage()); return jsonObject; } catch (JSONException e1) { e1.printStackTrace(); } e.printStackTrace(); } return result; }