簡體   English   中英

解析 JSON Issue 為 Android

[英]Parsing JSON Issue for Android

你好,Frnds 這是我在 iPhone 上使用 Xcode 並正確獲得響應的代碼,但問題是,當我使用相同的 url 和相同的 json 進行 android 開發時,我得到:-

{"code":"400","message":"Failed loading JSON. Special characters must not be included in the request. Please check the requested JSON."}

我認為這是我沒有發現的任何小技術問題。 我是 android 開發的新手,在過去的 15 天里我嘗試了 1000 次並且感到沮喪。 :-(:-(:-(:-(:-(:-(:-(:-(:-(:-( 誰能給我提供完整的解決方案和 android 的完整代碼。我將非常感謝你。

iPhone 的代碼是:

NSURL *url = [NSURL URLWithString:@"http://www.invoicera.com/app/api/check_json_api.php?token=7B92C122473A3D6F54E60D20AC5526D0"];


NSString *jsonRequest = [NSString stringWithFormat:@"&json_data=%@",[[NSString stringWithFormat:@"{\"listInvoice\":{\"client_id\":\"\",\"date_from\":\"\",\"date_to\":\"\",\"invoice_number\":\"\",\"invoice_record_status\":\"\",\"invoice_status\":\"\",\"page\":\"1\",\"per_page_record\":\"20\"}}"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

NSLog(@"%@",jsonRequest);

NSData *json_data = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];

NSLog(@"%@",json_data);

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];


[request setHTTPMethod:@"POST"];
[request setHTTPBody: json_data];
NSLog(@"%@",json_data);
// [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
//[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [json_data length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:[[jsonRequest stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]
                      dataUsingEncoding:NSUTF8StringEncoding 
                      allowLossyConversion:YES]];

// [NSURLConnection connectionWithRequest:[request autorelease] delegate:self];

NSURLConnection *nsUrlConnection=[[NSURLConnection alloc]
                                  initWithRequest:request 
                                  delegate:self];

// Successful connection.
if (nsUrlConnection) {

   // [self initSpinner];
   // [self spinBegin];

    NSMutableData *data = [[NSMutableData alloc] init];
    self.receivedData=data;
    [data release];
} 
// Unsuccessful connection.
else {

}  
// Clean up
[url release];
[request release];

編寫此代碼后,我可以從服務器獲得完美的響應。 但是對於 android 開發,我怎樣才能從服務器獲得相同的響應。 請為我提供完整的解決方案,完整代碼為 android。

{"@attributes":{"status":"200"},"invoices":{"@attributes":{"page":"1","per_page_record":"20","total_pages":"13","total_records":"246"},"invoice":[{"client":{"client_id":"421","organization":"max styles","address":"H-189,Vasundhara","billing_address":{"street":"H-189,Vasundhara","city":{},"state":{},"zip":........................etc etc etc.

這是 android 代碼:

public class JSONParser {

    String s1 = "{\"listInvoice\":{\"client_id\":\"\",\"date_from\":\"\",\"date_to\":\"\",\"invoice_number\":\"\",\"invoice_record_status\":\"\",\"invoice_status\":\"\",\"page\":\"1\",\"per_page_record\":\"20\"}}";

    public String payload;

    public JSONParser(String[]array) {
        this.payload = null;
    }

    public void excuteHttpPost() throws Exception {
        BufferedReader in = null;

        try {
            // Creating HTTP client
            JSONObject listobj = new JSONObject ();
            JSONObject listInvoice = new JSONObject ();
            listInvoice.put("client_id","");
            listInvoice.put("date_from","");
            listInvoice.put("date_to","");
            listInvoice.put("invoice_number","");
            listInvoice.put("invoice_record_status","");
            listInvoice.put("invoice_status","");
            listInvoice.put("page","1");
            listInvoice.put("per_page_record","10");
            listobj.put("listInvoice", listInvoice);

            HttpClient client = new DefaultHttpClient();
            HttpPost request = new HttpPost(ConstantList.invoicelistURL);

            List<NameValuePair> postParameters = new ArrayList<NameValuePair>(1);
            postParameters.add(new BasicNameValuePair("json_data", s1));

            Log.d("Http Response:", postParameters.toString());

            // Build JSON string

            request.setHeader("Content-type", "application/x-www-form-urlencoded");
            request.setEntity(new UrlEncodedFormEntity(postParameters));
            HttpResponse response = client.execute(request);

            // writing response to log
            Log.d("Http Response:", response.toString());
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line+NL);
            }
            in.close();
            payload = sb.toString();

        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                   e.printStackTrace();
                }
            }
        }
    }
}

問題是您根本不在請求中使用JSONObject listobj ,而是將s1添加到 post 參數。 使用此代碼:

postParameters.add(new BasicNameValuePair("json_data", listobj.toString()));

此外,將 integer 值明確地放入 JSONObject: listInvoice.put("page", 1); 而不是listInvoice.put("page", "1");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM