引入Gradle依赖:compile 'com.squareup.okhttp3:okhttp:3.4.1'
MainActivity代码如下:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "TAG";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* http-get请求
*绑定按钮的事件
* @param view
*/
public void httpGet(View view) {
new Thread() {
@Override
public void run() {
super.run();
String url = "http://www.baidu.com";
OkHttpClient client = new OkHttpClient();//创建okhttp实例
Request request = new Request.Builder()
.url(url).build();
Call call = client.newCall(request);
try {
Response response = call.execute();
if (response.isSuccessful()) {
Log.i(TAG, "httpGet: " + response.body().string());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
}
Response response = call.execute();这个是同步方式的,所以我开启了个子线程来执行,
否则会崩掉。。也可以不开启线程,那就可以这样做:
修改后MainActivity代码如下:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "TAG";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* get请求
*
* @param view
*/
public void httpGet(View view) {
String url = "http://www.baidu.com";
OkHttpClient client = new OkHttpClient();//创建okhttp实例
Request request = new Request.Builder()
.url(url).build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
//请求失败时调用
@Override
public void onFailure(Call call, IOException e) {
Log.i(TAG, "onFailure: " + e);
}
//请求成功时调用
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.i(TAG, "onResponse: " + "ss");
if (response.isSuccessful()) {
Log.i(TAG, "onResponse: " + response.body().string());
}
}
});
}
}
运行结果是一样的,其实这个也是同步操作的。、
自己搭个服务器吧。我用的是tomcat,访问自己的服务器。老是访问别人的服务器多没意思。哈哈。。
在eclipse先建个web工程,再创建个LoginServlet代码如下:
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class LoginServlet
*/
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public LoginServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("GET请求成功");
response.getWriter().append("GET请求成功");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/**
* 防止乱码
*/
response.setContentType("text/html;charset=utf-8");
response. setCharacterEncoding("UTF-8");
request. setCharacterEncoding("UTF-8");
System.out.println("Post请求成功");
String name=request.getParameter("name");
System.out.println(name);
response.getWriter().append("Post请求成功");
}
}
然后把这个web项目部署到tomcat中就好了,这样我们的简单的服务器就搭建好了。
修改后MainActivity代码如下:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "TAG";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* get请求
*
* @param view
*/
public void httpGet(View view) {
//换成自己的ip就行
String url = "http://10.104.4.1:8080/okhttp/LoginServlet";
OkHttpClient client = new OkHttpClient();//创建okhttp实例
Request request = new Request.Builder()
.url(url).build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
//请求失败时调用
@Override
public void onFailure(Call call, IOException e) {
Log.i(TAG, "onFailure: " + e);
}
//请求成功时调用
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.i(TAG, "onResponse: " + "ss");
if (response.isSuccessful()) {
Log.i(TAG, "onResponse: " + response.body().string());
}
}
});
}
/**
* post请求
* @param view
*/
public void httpPost(View view){
//换成自己的ip就行
String url = "http://10.104.4.1:8080/okhttp/LoginServlet";
OkHttpClient client = new OkHttpClient();//创建okhttp实例
FormBody body=new FormBody.Builder()
.add("name","张三")
.add("age","23")
.build();
Request request=new Request.Builder().post(body).url(url).build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
//请求失败时调用
@Override
public void onFailure(Call call, IOException e) {
Log.i(TAG, "onFailure: " + e);
}
//请求成功时调用
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
Log.i(TAG, "onResponse: " + response.body().string());
}
}
});
}
}
运行结果:
好了,一个简单的post请求演示完了,只是提交了个键值对到服务器中,接下来演示提交json数据到服务器中
修改后MainActivity代码如下:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "TAG";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* get请求
*
* @param view
*/
public void httpGet(View view) {
//换成自己的ip就行
String url = "http://10.104.4.1:8080/okhttp/LoginServlet";
OkHttpClient client = new OkHttpClient();//创建okhttp实例
Request request = new Request.Builder()
.url(url).build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
//请求失败时调用
@Override
public void onFailure(Call call, IOException e) {
Log.i(TAG, "onFailure: " + e);
}
//请求成功时调用
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.i(TAG, "onResponse: " + "ss");
if (response.isSuccessful()) {
Log.i(TAG, "onResponse: " + response.body().string());
}
}
});
}
/**
* post请求
* @param view
*/
public void httpPost(View view){
//换成自己的ip就行
String url = "http://10.104.4.1:8080/okhttp/LoginServlet";
OkHttpClient client = new OkHttpClient();//创建okhttp实例
FormBody body=new FormBody.Builder()
.add("name","张三")
.add("age","23")
.build();
Request request=new Request.Builder().post(body).url(url).build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
//请求失败时调用
@Override
public void onFailure(Call call, IOException e) {
Log.i(TAG, "onFailure: " + e);
}
//请求成功时调用
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
Log.i(TAG, "onResponse: " + response.body().string());
}
}
});
}
/**
* post请求 提交数据到服务器
* @param view
*/
public void httpPostJSON(View view){
String json="{\n" +
" \"name\": \"张三 \"\"age\": \"23 \"\n" +
"}";
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
//换成自己的ip就行
String url = "http://10.104.4.1:8080/okhttp/LoginServlet";
OkHttpClient client = new OkHttpClient();//创建okhttp实例
RequestBody body=RequestBody.create(JSON,json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
//请求失败时调用
@Override
public void onFailure(Call call, IOException e) {
Log.i(TAG, "onFailure: " + e);
}
//请求成功时调用
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
Log.i(TAG, "onResponse: " + response.body().string());
}
}
});
}
}
web工程下LoginServlet 类doPost方法
修改后如下:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/**
* 防止乱码
*/
response.setContentType("text/html;charset=utf-8");
response. setCharacterEncoding("UTF-8");
request. setCharacterEncoding("UTF-8");
/**
* 把请求的json数据读取出来。
*/
InputStream is=request.getInputStream();
BufferedReader reader=new BufferedReader(new InputStreamReader(is, "utf-8"));
String line=null;
StringBuffer sb=new StringBuffer();
while((line=reader.readLine())!=null){
sb.append(line);
}
System.out.println(sb.toString());
response.getWriter().append("Post请求成功");
}
运行效果:
接下来怎么把文件上传到服务器中:
/**
* 上传文件
*
* @param view
* @throws IOException
*/
public void postFile(View view) throws IOException {
/**
* 写数据到文件中,只是模拟下,
*/
File file = new File(getFilesDir(), "student.txt");
FileOutputStream fos = openFileOutput(file.getName(),MODE_PRIVATE);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos));
writer.write("你好啊,我不是程序员!!!");
writer.close();
fos.close();
/**
* 上传文件到服务器中
*/
MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8");
OkHttpClient client = new OkHttpClient();//获取OkHttpClient实例
RequestBody body = RequestBody.create(MEDIA_TYPE_MARKDOWN, file);
String uri = "http://10.104.65.140:8080/okhttp/LoginServlet";
final Request request = new Request.Builder().url(uri).post(body).build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i(TAG, "onFailure: "+e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.i(TAG, "onResponse: "+response.body().string());
}
});
}
运行结果:
终于写完了,我是名初学者,有不对的地方请指正。
我是跟着simple学的;
https://github.com/square/okhttp/tree/master/samples/guide/src/main/java/okhttp3/recipes