****我想将此JSON字符串传递给URL参数,以便Web服务器可以读取并保存数据库中的值。**
"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”);
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();
}
}
它还给我回复Code 500 谁能告诉我如何获得Param中的所有价值?**
答案 0 :(得分:0)
你可以使用我的班级:
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";
}
}
}
您可以从您的活动中运行此功能:
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);
答案 1 :(得分:0)
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;
}
}
}`
这是我的Web服务器代码。