Android凌空如何接收和发送一个json

时间:2016-07-20 01:42:53

标签: android json android-studio android-volley

我制作应用程序并在特定部分发送字符串并收到json。我使用VOLLEY 它运作良好,但现在我需要发送一个json。

这是我的代码:

 public static final String DATA_URL = "http://unynote.esy.es/cas/read_allorder.php?id=";  // THIS HAVE TO CHANGE JUST TO LOCALHOST:8080/LOGIN

下面:

public class Config {
public static final String DATA_URL = "http://unynote.esy.es/cas/read_allorder.php?id=";  // THIS HAVE TO CHANGE JUST TO LOCALHOST:8080/LOGIN
public static final String KEY_NAME = "COD_ALUMNO";
public static final String KEY_ADDRESS = "COD_ASIGNATURA";
public static final String KEY_VC = "GRUPO_SECCION";

public static final String KEY_AULA = "AULA";
public static final String KEY_DIA = "DIA";
public static final String KEY_INICIO = "INICIO";
public static final String KEY_FIN = "FIN";

public static final String JSON_ARRAY = "result";

 }

此处是VOLLEY CODE的一部分

public class TabsActivity extends AppCompatActivity implements  
 View.OnClickListener {

private EditText editTextId;
private Button buttonGet;
private TextView textViewResult;

private ProgressDialog loading;

int cont=1;
String[ ] contenido = new String[7];
String f="";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_mainint);

    editTextId = (EditText) findViewById(R.id.editTextId);
    buttonGet = (Button) findViewById(R.id.buttonGet);
    textViewResult = (TextView) findViewById(R.id.textViewResult);

    buttonGet.setOnClickListener(this);
}

private void getData() {
    String id = editTextId.getText().toString().trim();
    if (id.equals("")) {
        Toast.makeText(this, "Please enter an id", Toast.LENGTH_LONG).show();
        return;
    }
    loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);

    String url = Config.DATA_URL+editTextId.getText().toString().trim();

    StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            loading.dismiss();
            Toast.makeText(getBaseContext(), "si", Toast.LENGTH_LONG).show();

            showJSON(response);
        }
    },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(TabsActivity.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
                }
            });

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}

private void showJSON(String response){

   // Toast.makeText(getBaseContext(), response, Toast.LENGTH_LONG).show();

    String name="";
    String address="";
    String grupo = "";
    String aula = "";
    String dia = "";
    String inicio = "";
    String fin = "";



    try {
        Toast.makeText(getBaseContext(), "LOGIN... ", Toast.LENGTH_LONG).show();
        JSONObject jsonObject = new JSONObject(response);

        JSONArray ja = jsonObject.getJSONArray("orders");
        // JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
        for (int i = 0; i < ja.length(); i++) {
            JSONObject collegeData = ja.getJSONObject(i);
            name = collegeData.getString("id");
            address = collegeData.getString("item");
             grupo = collegeData.getString("GRUPO_SECCION");
             aula = collegeData.getString("AULA");
             dia = collegeData.getString("DIA");
             inicio = collegeData.getString("INICIO");
             fin = collegeData.getString("FIN");

            ///database
            DBAdapter db= new DBAdapter(this);

            db.open();
            long id = db.insertContact(address, aula,dia,inicio,fin );
            db.close();

            db.open();
            Cursor c = db.getAllContacts();
            if (c.moveToFirst())
            { do{
                contenido=getcontenido(c);

            }while (c.moveToNext());
            }
            db.close();
            cont= Integer.parseInt( contenido[0]);
            /// database

            /// alarms
            int [] time;
            time = parsetime(inicio);

            int horai = time[0];
            int minutoi = time[1];
            int diaa = getDay(dia);

            Calendar cal = Calendar.getInstance();
            cal.setTimeInMillis(System.currentTimeMillis());
            cal.set(Calendar.HOUR_OF_DAY, horai);
            cal.set(Calendar.MINUTE, minutoi);
            cal.set(Calendar.DAY_OF_WEEK, diaa);
            cal.add(Calendar.SECOND, 2);


            Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
            intent.putExtra("name", address);
            //intent.putExtra("curos bn",1);
            PendingIntent pendingIntent =
                    PendingIntent.getBroadcast(getBaseContext(),
                            cont+1, intent, PendingIntent.FLAG_UPDATE_CURRENT );




            AlarmManager alarmManager =
                    (AlarmManager)getSystemService(Context.ALARM_SERVICE);
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                    cal.getTimeInMillis(), 24 * 7 * 60 * 60 * 1000 , pendingIntent);


            ////alarms



            f=f+"codigo alumno:\t"+name+"\ncodigo/nombre curso:\t" +address+ "\ngrupo:\t"+grupo+"\naula:\t"
            +aula+"\ndia:\t"+dia+"\ninicio:\t"+inicio+"\nfin:\t"+fin+"\n:\t";

        }
        //  Toast.makeText(getBaseContext(),  collegeData.length(), Toast.LENGTH_LONG).show();
        //collegeData.toString();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    textViewResult.setText(f);
}

我刚刚发现STRING editTextId.getText()。这是每个用户的代码,但现在我需要发送带有该字符串的json。

'CCODUSU''45875621'

CCODUSU是标识符

3 个答案:

答案 0 :(得分:2)

我会看看StringRequests。以下是如何将事物发送到PHP文件的示例,该文件更新数据库,或者可以执行任何操作:

<强> SetMyStuff.java:

package com.example.your_app.database_requests;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;

import java.util.HashMap;
import java.util.Map;

public class SetMyStuff extends StringRequest {

    private static final String LOGIN_REQUEST_URL = "http://example.com/SetMyStuff.php";
    private Map<String, String> params;

    public SetMyStuff(String username, String password, Response.Listener<String> listener) {
        super(Request.Method.POST, LOGIN_REQUEST_URL, listener, null);
        params = new HashMap<>();
        params.put("username", username);
        params.put("password", password);
    }

    @Override
    public Map<String, String> getParams() {
        return params;
    }

}

调用此StringRequest:

Response.Listener<String> listener = new Response.Listener<String>() {

                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonResponse = new JSONObject(response);

                        boolean success = jsonResponse.getBoolean("success");

                        if (!success) {
                            Log.e(TAG, "Could not update stuff.");
                        } else {
                            Log.e(TAG, "Updated stuff.");
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            };
            SetMyStuff setMyStuffRequest = new SetMyStuff(username, password, listener);
            RequestQueue requestQueue = Volley.newRequestQueue(context);
            requestQueue.add(setMyStuffRequest);

收到此内容的PHP文件:

<?php

    $password = $_POST["password"];
    $username = $_POST["username"];

    $con = mysqli_connect("website.com", "dbusername", "dbpassword", "dbtable");

    $response = array();
    $response["success"] = false;

    /* Do something */
    $response["success"] = true;

    echo json_encode($response);
?>

答案 1 :(得分:0)

您的意思是说您需要发送包含JSON的{​​{1}},如果您想这样做,则必须拼写出完整且正确的editTextId.getText().toString().trim()

JSON

您发布的字符串不是'CCODUSU' '45875621' ,您需要将其修改为:

json

{"CCODUSU": "45875621"} 之后提交此字符串后,服务器将收到Config.DATA_URL参数,并且是id

答案 2 :(得分:0)

我也想出了同样的问题。在找到方法的过程中,我开发出了一种可以帮助你的方法。 如果要将json发布到服务器,则可以创建JsonObjectRequest:

apply plugin: 'java'
apply plugin: 'maven'
apply plugin: 'idea'
group 'com.test'
version '1.0'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
    mavenLocal()
}

apply from: 'dependencies.gradle'

configurations {
    providedCompile
}

dependencies {
    compile 'com.opencsv:opencsv:3.8'

    providedCompile 'org.apache.spark:spark-core_2.10:1.6.1'

    compile 'com.github.spullara.cli-parser:cli-parser:1.1'

    testCompile group: 'junit', name: 'junit', version: '4.11'
}

sourceSets.main.compileClasspath += configurations.providedCompile
sourceSets.test.compileClasspath += configurations.providedCompile
sourceSets.test.runtimeClasspath += configurations.providedCompile

jar {
    dependsOn configurations.runtime
    zip64 true
    from {
        (configurations.compile).collect {
            it.isDirectory() ? it : zipTree(it)
        }
    } {
        exclude "META-INF/license"
        exclude "META-INF/license/*"
        exclude "META-INF/LICENSE*"
        exclude "META-INF/*.DSA"
        exclude "META-INF/*.RSA"
    }
}

然后你可以在你的活动或片段中使用这个jave文件发送json并收到如下所示的响应:

./gradlew clean --debug

你可以收到json:

    21:11:27.805 [DEBUG] [org.apache.http.impl.conn.DefaultHttpClientConnectionOperator] Connecting to repo1.maven.org/151.101.24.209:443
    21:11:27.805 [DEBUG] [org.apache.http.conn.ssl.SSLConnectionSocketFactory] Connecting socket to repo1.maven.org/151.101.24.209:443 with timeout 0
    21:11:27.930 [DEBUG] [org.gradle.api.internal.artifacts.repositories.resolver.DefaultExternalResourceArtifactResolver] Loading file:/Users/user/.m2/repository/com/github/spullara/cli-parser/cli-parser/1.1/cli-parser-1.1.pom
    21:11:27.931 [DEBUG] [org.gradle.api.internal.artifacts.repositories.resolver.DefaultExternalResourceArtifactResolver] Loading file:/Users/user/.m2/repository/com/github/spullara/cli-parser/cli-parser/1.1/cli-parser-1.1.jar
    21:11:27.931 [DEBUG] [org.gradle.api.internal.artifacts.repositories.resolver.ExternalResourceResolver] No meta-data file or artifact found for module 'com.github.spullara.cli-parser:cli-parser:1.1' in repository 'MavenLocal'.
    21:11:27.943 [DEBUG] [org.gradle.api.internal.artifacts.ivyservice.resolveengine.oldresult.TransientConfigurationResultsBuilder] Flushing resolved configuration data in Binary store in /private/var/folders/tb/j1t6f2sd4yvf6tyhtj_81tkr0000gn/T/gradle3280928141968750531.bin. Wrote root com.test:project:1.0:compile.
    21:11:27.974 [ERROR] [org.gradle.BuildExceptionReporter] 
    21:11:27.974 [ERROR] [org.gradle.BuildExceptionReporter] FAILURE: Build failed with an exception.
    21:11:27.974 [ERROR] [org.gradle.BuildExceptionReporter] 
    21:11:27.974 [ERROR] [org.gradle.BuildExceptionReporter] * Where:
    21:11:27.974 [ERROR] [org.gradle.BuildExceptionReporter] Build file '/Users/user/workspace/project/build.gradle' line: 38
    21:11:27.975 [ERROR] [org.gradle.BuildExceptionReporter] 
    21:11:27.975 [ERROR] [org.gradle.BuildExceptionReporter] * What went wrong:
    21:11:27.975 [ERROR] [org.gradle.BuildExceptionReporter] Could not resolve all dependencies for configuration ':compile'.
    21:11:27.975 [ERROR] [org.gradle.BuildExceptionReporter] > Could not resolve com.opencsv:opencsv:3.8.
    21:11:27.975 [ERROR] [org.gradle.BuildExceptionReporter]   Required by:
    21:11:27.975 [ERROR] [org.gradle.BuildExceptionReporter]       com.test:project:1.0
    21:11:27.975 [ERROR] [org.gradle.BuildExceptionReporter]    > Could not resolve com.opencsv:opencsv:3.8.
    21:11:27.975 [ERROR] [org.gradle.BuildExceptionReporter]       > java.lang.ExceptionInInitializerError (no error message)
    21:11:27.976 [ERROR] [org.gradle.BuildExceptionReporter] > Could not resolve com.github.spullara.cli-parser:cli-parser:1.1.
    21:11:27.976 [ERROR] [org.gradle.BuildExceptionReporter]   Required by:
    21:11:27.976 [ERROR] [org.gradle.BuildExceptionReporter]       com.test:project:1.0
    21:11:27.976 [ERROR] [org.gradle.BuildExceptionReporter]    > Could not resolve com.github.spullara.cli-parser:cli-parser:1.1.
    21:11:27.976 [ERROR] [org.gradle.BuildExceptionReporter]       > Could not initialize class javax.crypto.JceSecurityManager
    21:11:27.976 [ERROR] [org.gradle.BuildExceptionReporter] 
    21:11:27.977 [ERROR] [org.gradle.BuildExceptionReporter] * Try:
    21:11:27.977 [ERROR] [org.gradle.BuildExceptionReporter] Run with --stacktrace option to get the stack trace. 
    21:11:27.978 [LIFECYCLE] [org.gradle.BuildResultLogger] 
    21:11:27.978 [LIFECYCLE] [org.gradle.BuildResultLogger] BUILD FAILED
    21:11:27.978 [LIFECYCLE] [org.gradle.BuildResultLogger] 
    21:11:27.978 [LIFECYCLE] [org.gradle.BuildResultLogger] Total time: 7.244 secs
    21:11:27.980 [DEBUG] [org.gradle.api.internal.artifacts.ivyservice.ivyresolve.memcache.InMemoryCachedRepositoryFactory] In-memory dependency metadata cache closed. Repos cached: 2, cache instances: 2, modules served from cache: 0, artifacts: 0

你可以获得标题:

var c = d3.line()
.interpolate("monotone")
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.close); }); 

VolleySingleton班

public class AppJSONObjectRequest extends JsonObjectRequest{

private Response.Listener<JSONObject> listener;
private Map<String, String> headers;

public AppJSONObjectRequest(int method, String url, JSONObject jsonObject, Response.Listener<JSONObject> reponseListener, Response.ErrorListener errorListener, Map<String, String> headers) {
    super(method, url, jsonObject, reponseListener, errorListener);
    this.headers = headers;
    this.listener = reponseListener;
}

@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
    try {
        String jsonString = new String(response.data,
                HttpHeaderParser.parseCharset(response.headers));
        return Response.success(new JSONObject(jsonString),
                HttpHeaderParser.parseCacheHeaders(response));
    } catch (UnsupportedEncodingException e) {
        return Response.error(new ParseError(e));
    } catch (JSONException je) {
        return Response.error(new ParseError(je));
    }
}

@Override
protected void deliverResponse(JSONObject response) {
    listener.onResponse(response);
}

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
    return headers;
}
}

只是你可以实现上面的示例......然后希望你能得到你想要的东西。它可能是复制粘贴代码,但它足以覆盖你的问题。