post请求
package com.bw.httputils;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import java.io.IOException;
/**
* Created by Administrator on 2016/6/14.
*/
public class Http {
private static String s;
private static String ss;
public static String httpuilts(String ur,String name,String pw,String tel) {
OkHttpClient oc=new OkHttpClient();
FormEncodingBuilder builder = new FormEncodingBuilder();
builder.add("uname",name);
builder.add("upwd",pw);
builder.add("utel",tel);
Request request = new Request.Builder()
.url(ur)
.post(builder.build())
.build();
Call call=oc.newCall(request);
Response response = null;
try {
response = call.execute();
if(response.isSuccessful()){
s = response.body().string();
return s;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
get请求
public static String okhttp(String st) {
//创建okHttpClient对象
OkHttpClient mOkHttpClient = new OkHttpClient();
//创建一个Request
final Request request = new Request.Builder()
.url(st)
.build();
//new call
Call call = mOkHttpClient.newCall(request);
//请求加入调度
try {
Response response=call.execute();
//如果请求成功
if(response.isSuccessful()){
//把字节转换成String
byte[] bytes = response.body().bytes();
ss=new String(bytes,"GB2312");
//直接请求返回字符串ss=response.body().string();
return ss;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}