Java JSON数据错误Android非法参数HttpClient

Java JSON数据错误Android非法参数HttpClient,java,android,json,http-get,Java,Android,Json,Http Get,我在Android中传输JSON时遇到问题。我在LogCat中收到以下错误 04-29 04:47:11.362: E/Trace(851): error opening trace file: No such file or directory (2) 04-29 04:47:12.243: I/System.out(851): 1 04-29 04:47:12.243: I/System.out(851): 2 04-29 04:47:12.303: W/System.err(851): j

我在Android中传输JSON时遇到问题。我在
LogCat
中收到以下错误

04-29 04:47:11.362: E/Trace(851): error opening trace file: No such file or directory (2)
04-29 04:47:12.243: I/System.out(851): 1
04-29 04:47:12.243: I/System.out(851): 2
04-29 04:47:12.303: W/System.err(851): java.lang.IllegalArgumentException: Illegal character in query     at index 42: http://SOME_WEBSITE/api/api.php?package=    {"key":"SOME_KEY","info":{"type":"user","login":{"password":"some_password","email":"test@gmail.    com"}},"request":"info"}
04-29 04:47:12.313: W/System.err(851):  at java.net.URI.create(URI.java:727)
04-29 04:47:12.333: W/System.err(851):  at org.apache.http.client.methods.HttpGet.<init>(HttpGet.    java:75)
04-29 04:47:12.333: W/System.err(851):  at com.example.jsontest.MainActivity.onCreate(MainActivity.    java:47)
04-29 04:47:12.333: W/System.err(851):  at android.app.Activity.performCreate(Activity.java:5104)
04-29 04:47:12.333: W/System.err(851):  at android.app.Instrumentation.callActivityOnCreate(    Instrumentation.java:1080)
04-29 04:47:12.333: W/System.err(851):  at android.app.ActivityThread.performLaunchActivity(    ActivityThread.java:2144)
04-29 04:47:12.343: W/System.err(851):  at android.app.ActivityThread.handleLaunchActivity(    ActivityThread.java:2230)
04-29 04:47:12.343: W/System.err(851):  at android.app.ActivityThread.access$600(ActivityThread.    java:141)
04-29 04:47:12.343: W/System.err(851):  at android.app.ActivityThread$H.handleMessage(ActivityThread.    java:1234)
04-29 04:47:12.343: W/System.err(851):  at android.os.Handler.dispatchMessage(Handler.java:99)
04-29 04:47:12.343: W/System.err(851):  at android.os.Looper.loop(Looper.java:137)
04-29 04:47:12.343: W/System.err(851):  at android.app.ActivityThread.main(ActivityThread.java:5041)
04-29 04:47:12.343: W/System.err(851):  at java.lang.reflect.Method.invokeNative(Native Method)
04-29 04:47:12.402: W/System.err(851):  at java.lang.reflect.Method.invoke(Method.java:511)
04-29 04:47:12.402: W/System.err(851):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(    ZygoteInit.java:793)
04-29 04:47:12.402: W/System.err(851):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-29 04:47:12.402: W/System.err(851):  at dalvik.system.NativeStart.main(Native Method)
04-29 04:47:12.402: I/System.out(851): Something is wrong
它必须是带有
GET
调用的东西。我不确定它到底是什么,但我所有的
系统.out
都打印到程序的那个部分

提前感谢您的帮助

java.lang.IllegalArgumentException: Illegal character in query
get请求中有一个在URL中不合法的字符。在GET请求中传递字符串之前,必须对字符串进行URL编码。有关详细信息,请参阅:


我希望这将对您有所帮助。在这个类中,两个方法都是编码的。在这种情况下,您还可以传递所需的参数

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;

public class JsonClient {

    public enum RequestMethod{
        GET,
        POST
    }

    private ArrayList <NameValuePair> params;
    private ArrayList <NameValuePair> headers;

    private String url;

    private int responseCode;
    private String message;

    private JSONObject jsonResponse;

    public JSONObject getResponse() {
        return jsonResponse;
    }

    public String getErrorMessage() {
        return message;
    }

    public int getResponseCode() {
        return responseCode;
    }

    public JsonClient(String url)
    {
        this.url = url;
        params = new ArrayList<NameValuePair>();
        headers = new ArrayList<NameValuePair>();
    }

    public void addParam(String name, String value)
    {
        params.add(new BasicNameValuePair(name, value));
    }

    public void addHeader(String name, String value)
    {
        headers.add(new BasicNameValuePair(name, value));
    }

    public void execute(RequestMethod method) throws Exception
    {
        switch(method) {
        case GET:
        {
            //add parameters
            String combinedParams = "";
            if(!params.isEmpty()){
                combinedParams += "?";
                for(NameValuePair p : params)
                {
                    String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),"UTF-8");
                    if(combinedParams.length() > 1)
                    {
                        combinedParams  +=  "&" + paramString;
                    }
                    else
                    {
                        combinedParams += paramString;
                    }
                }
            }

            HttpGet request = new HttpGet(url + combinedParams);

            //add headers
            for(NameValuePair h : headers)
            {
                request.addHeader(h.getName(), h.getValue());
            }

            executeRequest(request, url);
            break;
        }
        case POST:
        {
            HttpPost request = new HttpPost(url);

            //add headers
            for(NameValuePair h : headers)
            {
                request.addHeader(h.getName(), h.getValue());
            }

            if(!params.isEmpty()){
                request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            }

            executeRequest(request, url);
            break;
        }
        }
    }

    private void executeRequest(HttpUriRequest request, String url)
    {
        HttpClient client = new DefaultHttpClient();

        HttpResponse httpResponse;

        try {
            httpResponse = client.execute(request);
            responseCode = httpResponse.getStatusLine().getStatusCode();
            message = httpResponse.getStatusLine().getReasonPhrase();

            HttpEntity entity = httpResponse.getEntity();

            if (entity != null) {

                InputStream instream = entity.getContent();
                String  response = convertStreamToString(instream);
                jsonResponse = new JSONObject(response);

                // Closing the input stream will trigger connection release
                instream.close();
            }

        } catch (ClientProtocolException e)  {
            client.getConnectionManager().shutdown();
            e.printStackTrace();
        } catch (IOException e) {
            client.getConnectionManager().shutdown();
            e.printStackTrace();
        }catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private static String convertStreamToString(InputStream is) {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.net.urlcoder;
导入java.util.ArrayList;
导入org.apache.http.HttpEntity;
导入org.apache.http.HttpResponse;
导入org.apache.http.NameValuePair;
导入org.apache.http.client.ClientProtocolException;
导入org.apache.http.client.HttpClient;
导入org.apache.http.client.entity.UrlEncodedFormEntity;
导入org.apache.http.client.methods.HttpGet;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.client.methods.HttpUriRequest;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.apache.http.message.BasicNameValuePair;
导入org.apache.http.protocol.http;
导入org.json.JSONException;
导入org.json.JSONObject;
公共类JsonClient{
公共枚举请求方法{
得到,
邮递
}
私有数组列表参数;
私有数组列表头;
私有字符串url;
私人内部响应代码;
私有字符串消息;
私有JSONObject jsonResponse;
公共JSONObject getResponse(){
返回jsonResponse;
}
公共字符串getErrorMessage(){
返回消息;
}
public int getResponseCode(){
返回响应代码;
}
公共JsonClient(字符串url)
{
this.url=url;
params=新的ArrayList();
headers=newarraylist();
}
public void addParam(字符串名称、字符串值)
{
添加(新的BasicNameValuePair(名称、值));
}
public void addHeader(字符串名称、字符串值)
{
添加(新的BasicNameValuePair(名称、值));
}
public void execute(RequestMethod)引发异常
{
开关(方法){
案例获取:
{
//添加参数
字符串组合参数=”;
如果(!params.isEmpty()){
组合参数+=“?”;
用于(名称值对p:params)
{
字符串paramString=p.getName()+“=”+urlcoder.encode(p.getValue(),“UTF-8”);
如果(combinedParams.length()>1)
{
组合参数+=“&”+参数字符串;
}
其他的
{
combinedParams+=paramString;
}
}
}
HttpGet请求=新的HttpGet(url+组合参数);
//添加标题
对于(NameValuePair h:Header)
{
addHeader(h.getName(),h.getValue());
}
executeRequest(请求、url);
打破
}
个案职位:
{
HttpPost请求=新的HttpPost(url);
//添加标题
对于(NameValuePair h:Header)
{
addHeader(h.getName(),h.getValue());
}
如果(!params.isEmpty()){
setEntity(新的UrlEncodedFormEntity(params,HTTP.UTF_8));
}
executeRequest(请求、url);
打破
}
}
}
私有void executeRequest(HttpUriRequest请求,字符串url)
{
HttpClient=new DefaultHttpClient();
HttpResponse HttpResponse;
试一试{
httpResponse=client.execute(请求);
responseCode=httpResponse.getStatusLine().getStatusCode();
message=httpResponse.getStatusLine().getReasonPhrase();
HttpEntity entity=httpResponse.getEntity();
如果(实体!=null){
InputStream instream=entity.getContent();
字符串响应=convertStreamToString(流内);
jsonResponse=新的JSONObject(响应);
//关闭输入流将触发连接释放
流内关闭();
}
}捕获(客户端协议例外e){
client.getConnectionManager().shutdown();
e、 printStackTrace();
}捕获(IOE异常){
client.getConnectionManager().shutdown();
e、 printStackTrace();
}捕获(JSONException e){
e、 printStackTrace();
}
}
私有静态字符串convertStreamToString(InputStream为){
BufferedReader reader=新的BufferedReader(新的InputStreamReader(is));
StringBuilder sb=新的StringBuilder();
字符串行=null;
试一试{
而((line=reader.readLine())!=null){
sb.追加(第+行“\n”);
}
}捕获(IOE异常){
e、 printStackTrace();
}最后{
试一试{
is.close();
}捕获(IOE异常){
e、 printStackTrace();
}
}
使某人返回字符串();
}
}
试试:

String requestLink = "http://SOME_WEBSITE/api/api.php?package="+json.toString();
String finalRequestString = URLEncoder.encode(requestLink,"UTF-8");

如果您想将JSON用作“GET”(即作为url的一部分),则需要对字符串进行编码。例如,请注意,当您在浏览器中输入空白时,它会将其转换为
%20
。这是因为url不能包含空格

查看此帖子了解如何对url进行编码:

首先 您正在传递一个有空格的查询字符串
String requestLink = "http://SOME_WEBSITE/api/api.php?package="+json.toString();
String finalRequestString = URLEncoder.encode(requestLink,"UTF-8");
String requestLink = "http://SOME_WEBSITE/api/api.php?package="+Encoder.encode(json.toString(),"UTF-8");
package=    {