[英]Escaping quotes in java
我正在尝试拨打必须通过的网络服务电话
login.php?message=[{"email":"mikeymike@mouse.com","password":"tiger"}]
我已经使用反斜杠转义了这样的双引号
String weblink = "login.php?message=[{\"email\":\"mikeymike@mouse.com\",\"password\":\"tiger\"}]";
但是我仍然遇到错误。 我尝试过调用不需要任何带有双引号的数据的其他Web服务,并且它们可以正常工作,因此我可以确定问题出在此。 我也得到一个java.lang异常说
java.lang.Exception Indicates a serious configuration error.DateParseException An exception to indicate an error parsing a date string. DestroyFailedException Signals that the destroy() method failed
编辑:我已经尝试使用URLEncoder和JSON对象,但仍然收到错误
这是其余的代码
String HOST = "http://62.285.107.329/disaster/webservices/";
String weblink = "login.php?message=[{\"email\":\"mikeymike@mouse.com\",\"password\":\"tiger\"}]";
String result = callWebservice(weblink);
public String callWebservice(String weblink) {
String result = "";
try {
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 7500;
HttpConnectionParams.setConnectionTimeout(httpParameters,
timeoutConnection);
int timeoutSocket = 7500;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient client = new DefaultHttpClient(httpParameters);
HttpGet request = new HttpGet();
URI link = new URI(HOST + weblink);
request.setURI(link);
HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
result = rd.readLine();
} catch (Exception e1) {
e1.printStackTrace();
result = "timeout";
}
return result;
}
此外,Web服务还返回JSON对象,这也可能是导致错误的原因吗?
与其手动尝试并得到错误,不如使用JSONObject类和UrlEncoder的组合。
JSONObject json = new JSONObject();
json.put("email","mikeymike@mouse.com" );
json.put("password", "tiger");
String s = "login.php?message=" + UrlEncoder.encode(json.toString());
您必须使用%22
代替"
例如: login.php?message=[{%22email%22:%22mikeymike@mouse.com%22,%22password%22:%22tiger%22}]
"
不是网址中的有效字符。
更通用的解决方案是使用URLEncoder.encode("login.php?message=[{\\"email\\":\\"mikeymike@mouse.com\\",\\"password\\":\\"tiger\\"}]", "UTF8")
与Web服务通信时,需要对数据进行URL编码 。 在您的情况下,url编码将用%22
代替"
,但是如果您要添加其他特殊字符(例如%
,则该编码也会捕获这些字符。JDK中为此有一个Java类,称为URLEncoder 。
因此,基本上,您将要做的是使用URLEncoder.encode()
准备字符串,如下所示:
String weblink = URLEncoder.encode("login.php?message=[{\"email\":\"mikeymike@mouse.com\",\"password\":\"tiger\"}]");
现在字符串已编码,您应该能够将其发送到服务器,并让它理解您的意思。
对所有人表示歉意,但问题似乎出在我试图以错误的方式使用Web服务,因为它返回了JSON对象。
下面的代码对可能遇到此问题的任何人执行此操作的正确方法
String str="url";
try{
URL url=new URL(str);
URLConnection urlc=url.openConnection();
BufferedReader bfr=new BufferedReader(new InputStreamReader(urlc.getInputStream()));
String line;
while((line=bfr.readLine())!=null)
{
JSONArray jsa=new JSONArray(line);
for(int i=0;i<jsa.length();i++)
{
JSONObject jo=(JSONObject)jsa.get(i);
title=jo.getString("deal_title"); //tag name "deal_title",will return value that we save in title string
des=jo.getString("deal_description");
}
}
catch(Exeption e){
}
这个答案是从
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.