如何将我的 JSON 数组作为 URL 中的参数传递 [英] How to pass My JSON array as a parameter in URL

查看:40
本文介绍了如何将我的 JSON 数组作为 URL 中的参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

****我想将此 JSON 字符串传递给 URL 参数,以便 Web 服务器可以读取并保存数据库中的值.**

****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

这是我关于如何在 Android 应用程序中生成此字符串的完整代码.

试试{

        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");

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();
    }
}

它还给我响应代码 500谁能告诉我如何获得 Param 中的所有值?**

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

推荐答案

您可以使用我的课程:

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);

这篇关于如何将我的 JSON 数组作为 URL 中的参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆