您的位置:首页 > 理论基础 > 计算机网络

Okhttp使用

2016-05-06 12:59 501 查看
布局:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android" >

<Button
android:text="okhttp get请求1"
android:onClick="click1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button" />
<Button
android:text="okhttp get请求2"
android:id="@+id/button2"
android:onClick="click2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button"
android:layout_alignParentStart="true" />
<Button
android:text="okhttp post提交json"
android:onClick="post1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button2"
android:layout_alignParentStart="true"
android:id="@+id/button3" />
<Button
android:text="okhttp post提交键值对"
android:onClick="post2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button3"
android:layout_alignParentStart="true"
android:id="@+id/button4" />
<Button
android:text="okhttp post提交表单"
android:onClick="post3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button4"
android:id="@+id/button5" />
<Button
android:text="okhttp post提交文件"
android:onClick="post4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button5"
android:layout_alignParentStart="true"
android:id="@+id/button6" />
<Button
android:text="okhttp post分块处理"
android:onClick="post5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button6"
android:layout_alignParentStart="true"
android:id="@+id/button7" />
<Button
android:text="okhttp post提交流"
android:onClick="post6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button7"
android:layout_alignEnd="@+id/button7" />

</RelativeLayout>
代码:
package com.example.administrator.okdemo;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import com.google.gson.Gson;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.Headers;
import com.squareup.okhttp.MediaType;
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;

import java.io.File;
import java.io.IOException;

import javax.security.auth.login.LoginException;

import okio.BufferedSink;

public class MainActivity extends Activity {

private static final String TAG ="MainActivity" ;
//创建okHttpClient对象
OkHttpClient client = new OkHttpClient();
//创建一个Request
final Request request = new Request.Builder()
.url("http://yingligame.com/ChinaSanSha/listWords.do")
.build();
public Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case 1:

break;

case 2:
break;
}
super.handleMessage(msg);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

}

/**
* okhttp get请求方式1
* @param view
*/
public void click1(View view){
new Thread(){
@Override
public void run() {
try {
String  url="http://yingligame.com/ChinaSanSha/listWords.do";
Request request = new Request.Builder().url(url).build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
Log.e(TAG,response.body().string());

} else {
throw new IOException("Unexpected code " + response);
}

} catch (IOException e) {
e.printStackTrace();
}
}
}.start();

}

/**
* okhttp get请求方式2
* @param view
*/
public void click2(View view){
new Thread(){
@Override
public void run() {
//new call
Call call = client.newCall(request);
//请求加入调度
call.enqueue(new Callback()
{
@Override
public void onFailure(Request request, IOException e)
{

}
@Override
public void onResponse(final Response response) throws IOException
{
String htmlStr =  response.body().string();
Log.e(TAG,htmlStr);
/*
response.body().string() 返回的是字符串
response.body().byteStream() 返回的是inputstream
response.body().bytes()  返回的是二进制字节数组
更新UI需要使用handler或者runOnUiThread
*/
resolvejson(htmlStr);
}
});
}
}.start();
}

/**
* 解析json
* @param htmlStr json字符串
*/
private void resolvejson(String htmlStr) {
/*
第一种
Gson gson=new Gson();
javabean对象=gson.fromJson(getBaseContext(),javabean.class);
*/
/*
第二种
try {
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
int id = (Integer) object.get("id");
javabean = new JsonBeans();
javabean.setId(id);
list.add(javabean);
Log.e("TAG", list + "");
Log.e("TAG", "============================");
Message msg = new Message();
msg.obj = new String(1);
handler.sendMessage(msg);
}

} catch (Exception e) {
e.printStackTrace();
msg.obj = new String(2);
handler.sendMessage(msg);
}
*/

}
/**
* post提交json
*/
public void post1(View view){
new Thread(){
@Override
public void run() {
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(JSON,String.valueOf(R.string.json));
Request request = new Request.Builder()
.url("http://192.168.3.216:8080")
.post(body)
.build();
try {
Response  response = client.newCall(request).execute();
if (response.isSuccessful()) {
Log.e(TAG,"success");
}else{
throw new IOException("Unexpected code " + response);
}
} catch (IOException e) {
e.printStackTrace();
}

}

}.start();
}

/**
* post 提交键值对
* @param view
*/
public void post2(View view){
new Thread(){
@Override
public void run() {
RequestBody formBody = new FormEncodingBuilder()
.add("word", "666")
.add("nickname", "888")
.add("tel", "15946250162")
.build();

Request request = new Request.Builder()
.url("http://yingligame.com/ChinaSanSha/sendwordAjax.do")
.post(formBody)
.build();

Response response = null;
try {
response = client.newCall(request).execute();
if (response.isSuccessful()) {
Log.e(TAG,"success");
} else {
throw new IOException("Unexpected code " + response);
}
} catch (IOException e) {
e.printStackTrace();
}

}
}.start();
}

/**
* post 提交表单
* @param view
*/
public void post3(View view){
new Thread(){
@Override
public void run() {
RequestBody formBody = new FormEncodingBuilder()
.add("word", "666")
.add("nickname", "888")
.add("tel", "15946250162")
.build();
Request request = new Request.Builder()
.url("http://yingligame.com/ChinaSanSha/sendwordAjax.do")
.post(formBody)
.build();

Response response = null;
try {
response = client.newCall(request).execute();
if (!response.isSuccessful()){
throw new IOException("Unexpected code " + response);
}else{
Log.e(TAG,"success");
}
} catch (IOException e) {
e.printStackTrace();
}

}
}.start();

}

/**
* post 提交文件
* @param view
*/
public void post4(View view){
new Thread(){
@Override
public void run() {
MediaType MEDIA_TYPE_MARKDOWN
= MediaType.parse("text/x-markdown; charset=utf-8");
File file = new File("/storage/emulated/legacy/555.jpg");
Request request = new Request.Builder()
.url("http://192.168.3.216:8080")
.post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
.build();

Response response = null;
try {
response = client.newCall(request).execute();
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}else{
Log.e(TAG,"success");
}

} catch (IOException e) {
e.printStackTrace();
}

}
}.start();

}

/**
* post 分块处理
* @param view
*/
public void post5(View view){
new Thread(){
@Override
public void run() {
String IMGUR_CLIENT_ID = "XXX";
MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
RequestBody formBody = new FormEncodingBuilder()
.add("word", "666")
.add("nickname", "888")
.add("tel", "15946250162")
.build();
RequestBody requestBody = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addPart(
Headers.of("Content-Disposition", "form-data; name=\"title\""),
formBody)
.addPart(
Headers.of("Content-Disposition", "form-data; name=\"image\""),
RequestBody.create(MEDIA_TYPE_PNG, new File("storage/emulated/legacy/555.jpg")))
.build();

Request request = new Request.Builder()
.header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)
.url("http://yingligame.com/ChinaSanSha/sendwordAjax.do")
.post(requestBody)
.build();

try {
Response response = client.newCall(request).execute();
if (!response.isSuccessful()){
throw new IOException("Unexpected code " + response);
} else{
Log.e(TAG,"success");
}
} catch (IOException e) {
e.printStackTrace();
}

}
}.start();
}

/**
* post 提交流
* @param view
*/
public void post6(View view){
new Thread(){
@Override
public void run() {
final MediaType MEDIA_TYPE_MARKDOWN
= MediaType.parse("text/x-markdown; charset=utf-8");
RequestBody requestBody = new RequestBody() {
@Override public MediaType contentType() {
return MEDIA_TYPE_MARKDOWN;
}

@Override public void writeTo(BufferedSink sink) throws IOException {
sink.writeUtf8("Numbers\n");
sink.writeUtf8("-------\n");
for (int i = 2; i <= 997; i++) {
sink.writeUtf8(String.format(" * %s = %s\n", i, factor(i)));
}
}

private String factor(int n) {
for (int i = 2; i < n; i++) {
int x = n / i;
if (x * i == n) return factor(x) + " × " + i;
}
return Integer.toString(n);
}
};

Request request = new Request.Builder()
.url("http://192.168.3.216:8080")
.post(requestBody)
.build();

Response response = null;
try {
response = client.newCall(request).execute();
if (!response.isSuccessful()){
throw new IOException("Unexpected code " + response);
}else{
Log.e(TAG,"success");
}
} catch (IOException e) {
e.printStackTrace();
}

}
}.start();
}

}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: