Skip to content

Commit

Permalink
网络请求框架
Browse files Browse the repository at this point in the history
  • Loading branch information
hubeijiangcan committed Apr 28, 2017
1 parent f8dd6ca commit 6b00497
Show file tree
Hide file tree
Showing 15 changed files with 392 additions and 99 deletions.
5 changes: 4 additions & 1 deletion Summary/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
>

<application
android:name=".MApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
Expand All @@ -17,6 +18,8 @@
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity android:name=".activity.TestActivity"
android:theme="@style/AppThemeSwipeBack"></activity>
</application>

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>
20 changes: 12 additions & 8 deletions Summary/app/src/main/java/com/mitbbs/summary/MApplication.java
Original file line number Diff line number Diff line change
@@ -1,37 +1,41 @@
package com.mitbbs.summary;

import android.app.Application;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.DisplayMetrics;

/**
* Created by jc on 2017/4/21.
*/
public class MApplication extends Application {
public class MApplication extends Application {

private static MApplication mInstance;

SharedPreferences mPreferences;
public static float DENSITY = 0;
public static int WIDTH = 0;
public static int HEIGHT = 0;

@Override
public void onCreate() {
super.onCreate();
mInstance = this;
// mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
}

public static MApplication getInstance(){
return mInstance;
return mInstance;
}

public static void getMetrics(){
if(DENSITY != 0 && WIDTH != 0 && HEIGHT != 0)return;

DisplayMetrics displayMetrics = new DisplayMetrics();
displayMetrics = getInstance().getResources().getDisplayMetrics();
DENSITY = displayMetrics.density;
WIDTH = displayMetrics.widthPixels;
HEIGHT = displayMetrics.heightPixels;
displayMetrics = getInstance().getResources().getDisplayMetrics();
DENSITY = displayMetrics.density;
WIDTH = displayMetrics.widthPixels;
HEIGHT = displayMetrics.heightPixels;


}
}
140 changes: 132 additions & 8 deletions Summary/app/src/main/java/com/mitbbs/summary/OkHttpManeger.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,22 @@

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
Expand All @@ -34,6 +39,7 @@ private OkHttpManeger(){
handler = new Handler(Looper.getMainLooper());
}

//采用单例模式获取对象
public static OkHttpManeger getInstance(){
OkHttpManeger instance = null;
if (maneger == null){
Expand All @@ -44,34 +50,152 @@ public static OkHttpManeger getInstance(){
}
}
}
return instance;
return maneger;
}

/**
* 同步请求,在android开发中不常用
* @param url
* @return
*/
@Deprecated
public String syncGetByUrl(String url){
//构建一个request请求
Request request = new Request.Builder().url(url).build();
Response response = null;
try {
response = client.newCall(request).execute();//同步请求数据
if (response.isSuccessful()){
return response.body().string();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

private void post(final ResponseHandler callBack){
final Request request = new Request.Builder().url(StaticString.BASE_URL).build();

/**
* 表单提交
* @param params
* @param callBack
*/
public void post(Map<String, String> params, final ResponseHandler callBack){
start(callBack);
FormBody.Builder form_builder = new FormBody.Builder();//表单对象,包含以input开始的对象,以html表单为主
if (params != null && !params.isEmpty()){
for (Map.Entry<String,String> entry:params.entrySet()) {
form_builder.add(entry.getKey(),entry.getValue());
}
}
RequestBody request_body = form_builder.build();
final Request request = new Request.Builder().url(StaticString.BASE_URL).post(request_body).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
callBack.onFail(e);
fail(callBack,e);
}

@Override
public void onResponse(Call call, Response response) throws IOException {
if (response != null && response.isSuccessful()){
try {
JSONObject object = new JSONObject(response.body().string());
success(callBack,object);
} catch (JSONException e) {
fail(callBack,e);
}
}else {
fail(callBack,new RuntimeException("okHttpManeger post respone is null or fail"));
}
}
});
}

public JSONObject obtainJson(Object...objects){
JSONObject jsonObject = new JSONObject();
if (objects.length %2 != 0){
Log.e(TAG,"getJson参数个数出错");
return null;
}

try {
for (int i = 0; i<objects.length; i += 2){
jsonObject.put((String)objects[i],objects[i+1]);
}

}catch (Exception e){
e.printStackTrace();
return null;
}

return jsonObject;
}
/**
* Json提交
* @param params
* @param callBack
*/
public void post(JSONObject jsonObject,final ResponseHandler callBack){
start(callBack);
FormBody.Builder form_builder = new FormBody.Builder();//表单对象,包含以input开始的对象,以html表单为主
form_builder.add("msg", jsonObject == null?"":jsonObject.toString());
RequestBody request_body = form_builder.build();
final Request request = new Request.Builder().url(StaticString.BASE_URL).post(request_body).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
fail(callBack,e);
}

@Override
public void onResponse(Call call, Response response) throws IOException {
if (response != null && response.isSuccessful()){
try {
JSONObject object = new JSONObject(response.body().string());
callBack.onSuccess(object);
success(callBack,object);
} catch (JSONException e) {
callBack.onFail(e);
fail(callBack,e);
}
}else {
callBack.onFail(new RuntimeException("response is null"));
success(callBack,new JSONObject());
}
}
});
}
interface ResponseHandler{
private void start(final ResponseHandler callBack){
handler.post(new Runnable() {
@Override
public void run() {
callBack.onStart();
}
});
}

private void success(final ResponseHandler callBack,final JSONObject object){
handler.post(new Runnable() {
@Override
public void run() {
callBack.onSuccess(object);
callBack.onFinish();
}
});
}

private void fail(final ResponseHandler callBack, final Exception e){
handler.post(new Runnable() {
@Override
public void run() {
callBack.onFail(e);
callBack.onFinish();
}
});
}

/**
* 网络请求回调接口
*/
public interface ResponseHandler{
void onStart();
void onSuccess(JSONObject object);
void onFail(Exception e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,13 @@
*/
public class StaticString {

//线上
public static String BASE_DOMAIN = "www.rencai8.com";

//阿里云
// public static String BASE_DOMAIN = "123.57.5.76:8080";

public static String BASE_URL ="http://"+BASE_DOMAIN+"/App_service/service_menu.php";

public static final String BASE_URL = "";

}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,15 +1,65 @@
package com.mitbbs.summary.activity;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import com.mitbbs.summary.OkHttpManeger;
import com.mitbbs.summary.R;

import org.json.JSONObject;

public class MainActivity extends AppCompatActivity {
private ListView listView;
private OkHttpManeger maneger;
private TextView textView;
final String TAG = "MainActivity";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.tv_test);
if (maneger == null) maneger = OkHttpManeger.getInstance();
JSONObject jsonObject = maneger.obtainJson("reqType","search_job","occupation", "",
"min_degree", "", "created_date", "","name",
"","page",1+"");

maneger.post(jsonObject, new OkHttpManeger.ResponseHandler() {
@Override
public void onStart() {
Log.e(TAG,"onStart");
}

@Override
public void onSuccess(JSONObject object) {
Log.e(TAG,"onSuccess.object = "+object.toString());
}

@Override
public void onFail(Exception e) {
Log.e(TAG,"onFail"+((e == null)?"null":e.getCause()));

}

@Override
public void onFinish() {
Log.e(TAG,"onFinish");
}
});



textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,TestActivity.class));
}
});

}
}
Loading

0 comments on commit 6b00497

Please sign in to comment.