OKHttpUtil工具类

时间:2023-03-08 17:18:29

导入jar包下载链接 http://square.github.io/okhttp/

package com.common.util;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response; /**
* 利用okhttp进行get和post的访问
*
* @author cp
*
*/
public class OKHttpUtil { /**
* get请求
* @param url
* @return
*/
public static String httpGet(String url) {
String result = null;
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
try {
Response response = client.newCall(request).execute();
result = response.body().string();
} catch (Exception e) {
e.printStackTrace();
}
return result;
} /**
* post请求
* @param url
* @param data 提交的参数为key=value&key1=value1的形式
*/
public static String httpPost(String url, String data) {
String result = null;
OkHttpClient httpClient = new OkHttpClient();
RequestBody requestBody = RequestBody.create(MediaType.parse("text/html;charset=utf-8"), data);
Request request = new Request.Builder().url(url).post(requestBody).build();
try {
Response response = httpClient.newCall(request).execute();
result = response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
  1. package com.handkoo.util;
  2. import java.io.IOException;
  3. import okhttp3.MediaType;
  4. import okhttp3.OkHttpClient;
  5. import okhttp3.Request;
  6. import okhttp3.RequestBody;
  7. import okhttp3.Response;
  8. /**
  9. * 利用okhttp进行get和post的访问
  10. *
  11. * @author cp
  12. *
  13. */
  14. public class OKHttpUtil {
  15. /**
  16. * 发起get请求
  17. *
  18. * @param url
  19. * @return
  20. */
  21. public static String httpGet(String url) {
  22. String result = null;
  23. OkHttpClient client = new OkHttpClient();
  24. Request request = new Request.Builder().url(url).build();
  25. try {
  26. Response response = client.newCall(request).execute();
  27. result = response.body().string();
  28. } catch (Exception e) {
  29. e.printStackTrace();
  30. }
  31. return result;
  32. }
  33. /**
  34. * 发送httppost请求
  35. *
  36. * @param url
  37. * @param data 提交的参数为key=value&key1=value1的形式
  38. * @return
  39. */
  40. public static String httpPost(String url, String data) {
  41. String result = null;
  42. OkHttpClient httpClient = new OkHttpClient();
  43. RequestBody requestBody = RequestBody.create(MediaType.parse("text/html;charset=utf-8"), data);
  44. Request request = new Request.Builder().url(url).post(requestBody).build();
  45. try {
  46. Response response = httpClient.newCall(request).execute();
  47. result = response.body().string();
  48. } catch (IOException e) {
  49. e.printStackTrace();
  50. }
  51. return result;
  52. }
  53. }