HttpUrlConnection Java x Android
我在一个普通的java类和android中实现了这段代码HttpUrlConnection Java x Android,java,android,httpurlconnection,Java,Android,Httpurlconnection,我在一个普通的java类和android中实现了这段代码 public static String getURLPage(String urlString){ URL url; String ret = ""; try { url = new URL(urlString); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
public static String getURLPage(String urlString){
URL url;
String ret = "";
try {
url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream response = urlConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(
response));
for (String line; (line = reader.readLine()) != null;) {
ret += line;
}
reader.close();
return ret;
} catch (Exception e) {
return e.getLocalizedMessage();
}
}
代码在Java中正确返回页面,但在Android中返回错误代码403
我试图设置用户代理,但没有任何更改
有什么问题吗?//编辑(对不起,我第一次读到403错误)
与403错误问题无关,您可以使用Android中包含的。您拥有比java.net.HttpURLConnection更好的API
这里有一个例子
// imports from org.apache.http (http://hc.apache.org)
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.apache.http.client.HttpClient;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.HttpStatus;
int TIMEOUT = 2000;
String url= "http://your-url.com;
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
HttpConnectionParams.setConnectionTimeout(httpParameters, TIMEOUT);
HttpClient hc = new DefaultHttpClient(httpParameters);
// which HTTP request: GET or POST ?
//HttpPost post = new HttpPost(url);
HttpGet get = new HttpGet(url);
HttpResponse rp = hc.execute(get);
// example to show the result as a string
String resultAsString= EntityUtils.toString(rp.getEntity());
这没有直接的帮助,但邦廷的评论是正确的。您应该在使用java时查找标题,并在使用android时进行比较。
使用此命令获得的参数:
HttpResponse rp = hc.execute(get);
// compare the headerParams
Header[] requestHeader = get.getAllHeaders();
Header[] responseHeader = rp.getAllHeaders();
403表示服务器拒绝您的请求(“禁止”)。查看标题,如果不允许某些标题,请检查服务器配置。提示:在对字符串(
ret
变量)进行大量串联时,应使用,因为它比string
快得多。如果无法访问服务器配置,如何检查允许的标题?Thios给出了错误代码403。。。我设置User Agent=MOzilla仍然不工作我编辑我的答案并告诉你如何查找标题