我已经使用 HttpUrlConnection 实现了一个类来从google geocoding api获取一些数据。当我在Android上使用此代码时,它可以正常工作。但是,只要我在另一个"正常"中使用此代码java程序,我有时会得到状态代码400(BadRequest)。这是我的代码:
HttpURLConnection c = null;
StringBuilder sb = new StringBuilder();
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-length", "0");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.setConnectTimeout(timeout);
c.setReadTimeout(timeout);
c.connect();
int status = c.getResponseCode();
switch (status) {
case HttpURLConnection.HTTP_OK:
case HttpURLConnection.HTTP_CREATED:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
}
} catch (SocketTimeoutException ex){
// Handle ...
} catch (MalformedURLException ex) {
// Handle ...
} catch (IOException ex) {
// Handle ...
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
}
}
}
每当我使用网络浏览器尝试时,我都有可靠的互联网连接以及我用来接收数据的网址。 提前谢谢!
答案 0 :(得分:2)
错误请求通常是由于网址不足造成的。正如您所提到的,并非每个URL都会出现此错误,只会显示它们的视图。所以它必须与之相关。请尝试以下代码以确保正在使用的URL的正确编码:
function globalDisable(id,table_column,call_action){
// call_action is use for calling the related php function
// table_column is use for calling the column name of that table
//action_parm = {call_action:'disable',table_column:id}
var action_parm = {call_action: call_action,
table_column: table_column,
user_id: id};
$.ajax({
type:'POST',
url:'post.php',
data:action_parm,
success: function(response){
}
});
}