0

我得到的错误是

请求失败:java.lang.IllegalArgumentException:索引 42 处查询中的非法参数:http:/10.0.2.2:8080/webservice2.php?json={\"UserName\":1,\"FullName\":2} "

main.java

package com.hamdyghanem.httprequest;

import java.*(etc etc)

public class Main extends Activity {
/** Called when the activity is first created. */
public int iLanguage = 0;
TextView lbl;
Typeface arabicFont = null;
int TIMEOUT_MILLISEC = 10000; // = 10 seconds

@Override
public void onCreate(Bundle savedInstanceState) {
    try {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        getWindow().setLayout(LayoutParams.FILL_PARENT,
                LayoutParams.FILL_PARENT);
        // ////
        arabicFont = Typeface.createFromAsset(getAssets(),
                "fonts/DroidSansArabic.ttf");

        lbl = (TextView) findViewById(R.id.lbl);
        //

    } catch (Throwable t) {
        Toast.makeText(this, "Request failed: " + t.toString(),
                Toast.LENGTH_LONG).show();
    }
}

public void clickbuttonRecieve(View v) {
    try {
        JSONObject json = new JSONObject();
        json.put("UserName", "test2");
        json.put("FullName", "1234567");
        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams,
                TIMEOUT_MILLISEC);
        HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
        HttpClient client = new DefaultHttpClient(httpParams);

        String url = "http://10.0.2.2:8080/webservice2.php?json = {\"UserName\":1,\"FullName\":2}";


        HttpPost request = new HttpPost(url);
        request.setEntity(new ByteArrayEntity(json.toString().getBytes(
                "UTF8")));
        request.setHeader("json", json.toString());
        HttpResponse response = client.execute(request);
        HttpEntity entity = response.getEntity();
        // If the response does not enclose an entity, there is no need
        if (entity != null) {
            InputStream instream = entity.getContent();

            String result = RestClient.convertStreamToString(instream);
            Log.i("Read from server", result);
            Toast.makeText(this,  result,
                    Toast.LENGTH_LONG).show();
        }
    } catch (Throwable t) {
        Toast.makeText(this, "Request failed: " + t.toString(),
                Toast.LENGTH_LONG).show();
    }
}

public void clickbutton(View v) {
    try {
        Log.i(getClass().getSimpleName(), "send  task - start");
        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams,
                TIMEOUT_MILLISEC);
        HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
        //
        HttpParams p = new BasicHttpParams();
        // p.setParameter("name", pvo.getName());
        p.setParameter("user", "1");

        // Instantiate an HttpClient
        HttpClient httpclient = new DefaultHttpClient(p);
        String url = "http://10.0.2.2:8080/webservice1.php?user=1&format=json";
        HttpPost httppost = new HttpPost(url);

        // Instantiate a GET HTTP method
        try {
            Log.i(getClass().getSimpleName(), "send  task - start");
            //
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
                    2);
            nameValuePairs.add(new BasicNameValuePair("user", "1"));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            String responseBody = httpclient.execute(httppost,
                    responseHandler);
            // Parse
            JSONObject json = new JSONObject(responseBody);
            JSONArray jArray = json.getJSONArray("posts");
            ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();

            for (int i = 0; i < jArray.length(); i++) {
                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject e = jArray.getJSONObject(i);
                String s = e.getString("post");
                JSONObject jObject = new JSONObject(s);

                map.put("idusers", jObject.getString("idusers"));
                map.put("UserName", jObject.getString("UserName"));
                map.put("FullName", jObject.getString("FullName"));

                mylist.add(map);
            }
            Toast.makeText(this, responseBody, Toast.LENGTH_LONG).show();

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // Log.i(getClass().getSimpleName(), "send  task - end");

    } catch (Throwable t) {
        Toast.makeText(this, "Request failed: " + t.toString(),
                Toast.LENGTH_LONG).show();
    }

}

public class Data {
    // private List<User> users;
    public List<User> users;

    // +getters/setters
}

static class User {
    String idusers;
    String UserName;
    String FullName;

    public String getUserName() {
        return UserName;
    }

    public String getidusers() {
        return idusers;
    }

    public String getFullName() {
        return FullName;
    }

    public void setUserName(String value) {
        UserName = value;
    }

    public void setidusers(String value) {
        idusers = value;
    }

    public void setFullName(String value) {
        FullName = value;
    }
}
}

webservice2.php

<?php 
//http://localhost:8080/sample1/webservice2.php?json= {%22UserName%22:1,%22FullName%22:2}
//$json=$_GET ['json'];
$json = file_get_contents('php://input');
$obj = json_decode($json);

//echo $json;


//Save
$con = mysql_connect('localhost','root','123456') or die('Cannot connect to the DB');
mysql_select_db('test',$con);

/* grab the posts from the db */
//$query = "SELECT post_title, guid FROM wp_posts WHERE post_author = $user_id AND post_status = 'publish' ORDER BY ID DESC LIMIT $number_of_posts";
mysql_query("INSERT INTO `test`.`users` (UserName, FullName)
    VALUES ('".$obj->{'UserName'}."', '".$obj->{'FullName'}."')");

mysql_close($con);
//
//$posts = array($json);
$posts = array(1);
header('Content-type: application/json');
echo json_encode(array('posts'=>$posts));

?>
4

2 回答 2

1

您应该转义您的 uri 字符。在 Android 上,您可以这样做:

String json = URLEncoder.encode("{\"UserName\":1,\"FullName\":2}", "utf-8");
String url = "http://10.0.2.2:8080/webservice2.php?json=" + json;
于 2013-04-24T00:41:36.450 回答
0

Illegal argument in Query at at index 42: ——这是重要的一点。就是说 URI 中的第 43 个(从 0 开始)字符(恰好是反斜杠)在这种情况下是非法的。根据这个库,URI 似乎不允许包含反斜杠。(这似乎是不正确的:见https://www.rfc-editor.org/rfc/rfc3986#section-2.1

你有两个选择:

  • 使用请求正文而不是查询字符串来包含 JSON 数据。
  • 转义 URI 中的反斜杠,将它们替换为%5C(尽管您可能应该为此使用现有的库/函数)。

就个人而言,我会选择第一个。一些 HTTP 服务器对请求 URI 的长度有限制,如果您想传输超过该限制的数据,这可能会很烦人。另外,您无需担心百分比编码。

此外,您的 PHP 中存在 SQL 注入漏洞mysql_query(...)。想象一下,如果我上传的 JSON 是{"UserName":"');DROP TABLE test.users;--"}. 您应该改用 mysqli_* 函数。见http://bobby-tables.com/

于 2013-04-24T00:32:38.387 回答