How to pass My JSON array as a parameter in URL

2019-08-20 07:32发布

****I Want to pass this JSON String to URL Parameters so the Web Server Can read and save the Values in Database.**

"data": [{
    "Id": "000039",
    "Name": "6502418"
}, {//Json Array
    "Id": "000037",
    "Name": "6502418"
},   {
    "Id": "000039",
    "Name": "6502418"
}]//Json array

Here is my Full Code Of how to Make this String In Android Application.

try {

        ds = new DataSource(cont);

        final URL url = new URL("http://asd.mo:1980/MOB/SendDoc.aspx");

        con = (HttpURLConnection) url.openConnection();

        Log.v("jarvis","Connection Check"+ con);

        con.setDoInput(true);

        con.setDoInput(true);

        con.setChunkedStreamingMode(0);

        con.addRequestProperty("Content-Type","application/json;charset=utf-8");

con.setRequestMethod("POST");

        ds.open();


        Cursor cursor = ds.send();  //cursor hold all your data

        JSONObject jobj ;
        JSONArray arr = new JSONArray();
        cursor.moveToFirst();
        while(cursor.moveToNext()) {
            jobj = new JSONObject();
            jobj.put("Id",cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_DA_DOC_ID)));
            jobj.put("Name", cursor.getString(cursor.getColumnIndex(DatabaseHelper.COL_DA_EMP_ID)));
            arr.put(jobj);
        }
        jobj = new JSONObject();
        jobj.put("data", arr);
        String st = jobj.toString();
        OutputStream out = new BufferedOutputStream(con.getOutputStream());
        out.write(st.toString().getBytes());
        Log.v("jarvis","Json string" + st.toString()); //from here I grab my JSON Array i want to throw this in URL as paramaters
        out.flush();
        out.close();
        ds.close();
        int result =con.getResponseCode();
        Log.v("jarvis","ResponceCode = " + result);// Show me 500.
        if (result==200){
            InputStream in = new BufferedInputStream(con.getInputStream());
            reader = new BufferedReader(new InputStreamReader(in));
            StringBuilder sb = new StringBuilder();
            String line= null;
            while ((line = reader.readLine()) != null){
                Status=line;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return Status;
}
@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
    if (result != null){
        Toast.makeText(cont,"Data Save SuccessFully",Toast.LENGTH_LONG).show();
    }else{
        Toast.makeText(cont,"Data didnot Save.Please Check Connection",Toast.LENGTH_LONG).show();
    }
}

It also give me response Code 500 Can anyone please tell me how I am getting all the values in Param?**

标签: android json url
2条回答
等我变得足够好
2楼-- · 2019-08-20 07:45

You can use my class:

public class HttpHelperConnection {

static String response = "";

//metodo pubblico per ottenere la risposta dal server settando tutti i parametri necessari

/**
 *
 * @param url
 * @param method
 * @param post_params
 * @param connection_timeout
 * @param reading_timeout
 * @return
 */
public static String getSyncResponse(String url, String method, HashMap<String, String> post_params,
        long connection_timeout, long reading_timeout){

    response = "";
    response = StartConnection(url, method, post_params, connection_timeout, reading_timeout);
    return response;
}

public static String getAsyncResponse(String url, String method, HashMap<String, String> post_params,
        long connection_timeout, long reading_timeout){

    new Thread(() -> {
        response = "";
        response = StartConnection(url, method, post_params, connection_timeout, reading_timeout);
    }).start();
    return response;
}

private static String StartConnection(String url, String method, HashMap<String, String> post_params,
        long connection_timeout, long reading_timeout){

    String localResponse = "";

    try{
        URL url_encoded = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) url_encoded.openConnection();
        conn.setReadTimeout((int)reading_timeout);
        conn.setConnectTimeout((int)connection_timeout);
        conn.setRequestMethod(method);//il metodo si occupa da solo di inviare la stringa nel metodo richiesto
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.addRequestProperty("User-Agent", "Chrome");
        conn.setRequestProperty("Accept-Encoding", "identity");


        try (OutputStream out_stream = conn.getOutputStream(); 
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out_stream, "UTF-8"))) {
            writer.write(ricevoServerLoginResponse(post_params));
            writer.flush();
        }catch(IOException e){
           System.out.print(e.toString());
        }

        if (conn.getResponseCode() == HttpsURLConnection.HTTP_OK) {

        }else {
            localResponse=null;
            System.out.println("Error to connect: " + Integer.toString(conn.getResponseCode()));
        }
        HttpHelperConnection class_conn = new HttpHelperConnection();
        String return_code = class_conn.decodeUrlCode(conn.getResponseCode());
        if(return_code.equals("OK")){
            String line;
            InputStreamReader stream_reader = new InputStreamReader(conn.getInputStream());
            if (!url_encoded.getHost().equals(conn.getURL().getHost()))
                System.out.println("redirectered");//nel caso il browser richiede un'autenticazione
            BufferedReader br=new BufferedReader(stream_reader);
            while ((line=br.readLine()) != null) {
                localResponse+=line;
            }
        }else
            localResponse = "error: " + return_code;
    }catch(IOException e){
        System.out.print(e.toString());
    }
    return localResponse;
}

//metodo privato per creare la stringa per i dati passati in post
private static String ricevoServerLoginResponse(HashMap<String, String> params) 
            throws UnsupportedEncodingException {
    StringBuilder result = new StringBuilder();
    boolean first = true;
    for(Map.Entry<String, String> entry : params.entrySet()){//passo ogni dato interno all'hash map
        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
    }

    return result.toString();
}

private String decodeUrlCode(int res_code){
    switch(res_code){
        case HttpsURLConnection.HTTP_OK : 
            return "OK";
        case HttpsURLConnection.HTTP_ACCEPTED :
            return "HTTP_ACCEPTED";
        case HttpsURLConnection.HTTP_BAD_GATEWAY :
            return "HTTP_BAD_GATEWAY";
        case HttpsURLConnection.HTTP_BAD_METHOD :
            return "HTTP_BAD_METHOD";
        case HttpsURLConnection.HTTP_BAD_REQUEST :
            return "HTTP_BAD_REQUEST";
        case HttpsURLConnection.HTTP_CLIENT_TIMEOUT :
            return "HTTP_CLIENT_TIMEOUT";
        case HttpsURLConnection.HTTP_CONFLICT :
            return "HTTP_CONFLICT";
        case HttpsURLConnection.HTTP_CREATED :
            return "HTTP_CREATED";
        case HttpsURLConnection.HTTP_ENTITY_TOO_LARGE :
            return "HTTP_ENTITY_TOO_LARGE";
        case HttpsURLConnection.HTTP_FORBIDDEN :
            return "HTTP_FORBIDDEN";
        case HttpsURLConnection.HTTP_GATEWAY_TIMEOUT :
            return "HTTP_GATEWAY_TIMEOUT";
        case HttpsURLConnection.HTTP_GONE :
            return "HTTP_GONE";
        case HttpsURLConnection.HTTP_INTERNAL_ERROR :
            return "HTTP_INTERNAL_ERROR";
        case HttpsURLConnection.HTTP_LENGTH_REQUIRED :
            return "HTTP_LENGTH_REQUIRED";
        case HttpsURLConnection.HTTP_MOVED_PERM :
            return "HTTP_MOVED_PERM";
        case HttpsURLConnection.HTTP_MOVED_TEMP :
            return "HTTP_MOVED_TEMP";
        case HttpsURLConnection.HTTP_MULT_CHOICE :
            return "HTTP_MULT_CHOICE";
        case HttpsURLConnection.HTTP_NOT_ACCEPTABLE :
            return "HTTP_NOT_ACCEPTABLE";
        case HttpsURLConnection.HTTP_NOT_AUTHORITATIVE :
            return "HTTP_NOT_AUTHORITATIVE";
        case HttpsURLConnection.HTTP_NOT_FOUND :
            return "HTTP_NOT_FOUND";
        case HttpsURLConnection.HTTP_NOT_IMPLEMENTED :
            return "HTTP_NOT_IMPLEMENTED";
        case HttpsURLConnection.HTTP_NOT_MODIFIED :
            return "HTTP_NOT_MODIFIED";
        case HttpsURLConnection.HTTP_NO_CONTENT :
            return "HTTP_NO_CONTENT";
        case HttpsURLConnection.HTTP_PARTIAL :
            return "HTTP_PARTIAL";
        case HttpsURLConnection.HTTP_PAYMENT_REQUIRED :
            return "HTTP_PAYMENT_REQUIRED";
        case HttpsURLConnection.HTTP_PRECON_FAILED :
            return "HTTP_PRECON_FAILED";
        case HttpsURLConnection.HTTP_PROXY_AUTH :
            System.out.println("HTTP_PROXY_AUTH");
            return "HTTP_PROXY_AUTH";
        case HttpsURLConnection.HTTP_REQ_TOO_LONG :
            return "HTTP_REQ_TOO_LONG";
        case HttpsURLConnection.HTTP_RESET :
            return "HTTP_RESET";
        case HttpsURLConnection.HTTP_SEE_OTHER :
            return "HTTP_SEE_OTHER";
        case HttpsURLConnection.HTTP_UNAUTHORIZED:
            return "HTTP_UNAUTHORIZED";
        case HttpsURLConnection.HTTP_UNAVAILABLE :
            return "HTTP_UNAVAILABLE";
        case HttpsURLConnection.HTTP_UNSUPPORTED_TYPE :
            return "HTTP_UNSUPPORTED_TYPE";
        case HttpsURLConnection.HTTP_USE_PROXY :
            return "HTTP_USE_PROXY";
        case HttpsURLConnection.HTTP_VERSION :
            return "HTTP_VERSION";
        default : 
            return "UNKNOWN_ERROR";
    }
}
}

You can run this from your Activity:

JSONObject jsobj;
String jsonString = jsonobj.toStirng();

HashMap<String, String> postParams = new HashMap<>();

postParams.put("datas", jsonString);

int connectionTimeout = 1000;
int readingTimeout = 1000;

//If you want connection in your thread
String resposne = HttpHelperConnection.getSyncResponse("https://yourUrl", "POST" , postParams, 1000 , 1000);

//If you want the connection in another thread
response = HttpHelperConnection.getAsyncResponse("https://yourUrl", "POST" , postParams, 1000 , 1000);
查看更多
smile是对你的礼貌
3楼-- · 2019-08-20 07:57
     namespace Andro
   {
public partial class SendDoc : System.Web.UI.Page
{
        string DocID1 = "";
        string EMPID1 = "";
        string conStr1 = "@D;
    protected void Page_Load(object sender, EventArgs e)
    {
        RcvData(DocID1, EMPID1);
    }            

    public int RcvData(string DocID, string EMPID)
        {
            DocID = DocID1; 
            EMPID = EMPID1; 
        int status = 0;
        SqlConnection con = new SqlConnection(this.conStr1);
        SqlCommand cmd = new SqlCommand();
        try
        {
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            //tablename and insetrt into respective Cloumen
            cmd = new SqlCommand("Insert into sms(UserID, EmpID, DATETIME, Lon, Lat, sa, PhoneNum,CoID) Values(@userID,@EmpID,@DATETIME,@Lon,@Lat,@sa,@PhoneNum,@CoID)", con);
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.AddWithValue("@userID", DocID);
            cmd.Parameters.AddWithValue("@EmpID", EMPID);
            cmd.Parameters.AddWithValue("@DATETIME", DATE);
            cmd.Parameters.AddWithValue("@Lon", LON);
            cmd.Parameters.AddWithValue("@Lat", LAT);
            cmd.Parameters.AddWithValue("@SA", SA);
            cmd.Parameters.AddWithValue("@CoID", COID);
            cmd.Parameters.AddWithValue("@PhoneNum", PHONENUM);
            cmd.ExecuteReader();
            status = 1;
        }
        catch (Exception e)
        {

            throw e;
        }
        finally
        {
            con.Close();
            cmd.Dispose();
        }
        return status;

        }
}

}`

here is my Web Server Code.

查看更多
登录 后发表回答